【发布时间】:2014-07-14 04:17:25
【问题描述】:
我想知道如何导入 JSON 文件,然后将其保存到有序的 CSV 文件中,其中包含标题行和下面的适用数据。
JSON 文件如下所示:
[
{
"firstName": "Nicolas Alexis Julio",
"lastName": "N'Koulou N'Doubena",
"nickname": "N. N'Koulou",
"nationality": "Cameroon",
"age": 24
},
{
"firstName": "Alexandre Dimitri",
"lastName": "Song-Billong",
"nickname": "A. Song",
"nationality": "Cameroon",
"age": 26,
etc. etc. + } ]
注意有多个“键”(名字、姓氏、昵称等)。我想创建一个 CSV 文件,以这些文件作为标题,然后在下面的行中创建适用的信息,每一行都有玩家的信息。
这是我目前为 Python 编写的脚本:
import urllib2
import json
import csv
writefilerows = csv.writer(open('WCData_Rows.csv',"wb+"))
api_key = "xxxx"
url = "http://worldcup.kimonolabs.com/api/players?apikey=" + api_key + "&limit=1000"
json_obj = urllib2.urlopen(url)
readable_json = json.load(json_obj)
list_of_attributes = readable_json[0].keys()
print list_of_attributes
writefilerows.writerow(list_of_attributes)
for x in readable_json:
writefilerows.writerow(x[list_of_attributes])
但是当我运行它时,我得到一个“TypeError: unhashable type:'list'”错误。我还在学习 Python(显然我想)。我在网上环顾四周(找到this),如果没有明确说明我想打印什么键,我似乎无法弄清楚该怎么做......我不想单独列出每个......
感谢您的任何帮助/想法!如果我可以澄清或提供更多信息,请告诉我。
【问题讨论】: