2016-08-22 78 views
1

我有一個JSON文件,其中包含一個包含許多鍵值對的字典。我想寫它到一個單一的CSV。一種方法是簡單地遍歷每個鍵:從JSON到CSV的字典

csvwriter.writerow([f["dict"]["key1"], f["dict"]["key2"], 
        f["dict"]["key3"], ... ]) 

這將是非常乏味的。

另一種可能性就是使用

csvwriter.writerow([f["dict"].values()]) 

,但它的一切寫入CSV文件中的一列,這是沒有幫助的。

有沒有辦法將每個值寫入CSV文件的一列?

+0

是否到保存在JSON文件需要按鍵的順序?如果不是,什麼決定了它們在CSV文件的列中出現的順序? – martineau

+0

沒有。似乎是隨機的。 – wwl

+0

嗯,好像有/允許數據出現在CSV的隨機列會使事後難以處理。 – martineau

回答

3

你可能想在正式文件中使用csv.DictWriter

的例子是相當直接:

import csv 

with open('names.csv', 'w') as csvfile: 
    fieldnames = ['first_name', 'last_name'] 
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames) 

    writer.writeheader() 
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) 
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) 
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'}) 

請注意,您必須提供fieldnames構造。如果你確定你所有的字典都有相同的鍵並且不關心輸出的順序,那麼你可以使用list(first_dict)來獲得列名,否則,你會想出一種方法來指定他們更明確。

1

Pandas適合這種事情。

我會將JSON文件讀入熊貓數據框(link)。然後將其編寫爲CSV(link)。

import pandas as pd 

#read in the json 
df = pd.read_json("json_path_here") 

# write the csv 
df.to_csv("csv_path_here") 
1

相當於你的代碼:

csvwriter.writerow(f["dict"].values()) 

注:對於這一點,你的字典應該是collections.OrderedDict因爲Python默認的字典是沒有順序的。因此,您將在每一行中以不同的順序結束。

或者,更好的方式來實現這一目標是使用DictWriter(您不需要有序字典):

csvwriter.writerow(f["dict"]) 
+0

我正在使用Python 2.7,當我輸入星號時,它會顯示「SyntaxError:Invalid Syntax」。有什麼我需要做的嗎? – wwl

+1

你可以跟我分享'f'的價值嗎?只要做'打印f'並與我分享 –

+0

{「stats」:{「item1」:3153,「totalPlayerScore」:0,...}} – wwl

0

這是沒有必要使用csv.DictWriter。以下是在Python 2和Python 3中都可以使用的示例,展示瞭如何創建一個CSV文件,該文件將按照它們在JSON文件中出現的順序自動生成鍵/值對(而不是需要手動定義的fieldnames列表):

from collections import OrderedDict 
import csv 
import json 
from io import StringIO 

# in-memory JSON file for testing 
json_file = StringIO(u'{"dict": {"First": "value1", "Second": "value2",' 
           '"Third": "value3", "Fourth": "value4"}}') 

# read file and preserve order by using OrderedDict 
json_obj = json.load(json_file, object_pairs_hook=OrderedDict) 

with open('pairs.csv', 'w') as csvfile: 
    writer = csv.writer(csvfile) 
    writer.writerow(json_obj["dict"].keys()) # header row 
    writer.writerow(json_obj["dict"].values()) 

pairs.csv文件的內容寫到:

First,Second,Third,Fourth 
value1,value2,value3,value4