Python - 将JSON转换为CSV表格?

0 投票
2 回答
1677 浏览
提问于 2025-04-18 13:11

我在想怎么把一个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. + } ]

注意,这里有多个“键”(比如firstName、lastName、nickname等等)。我想创建一个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(显然我还很菜)。我在网上查了一下(找到了这个),但似乎无法弄明白怎么做,而不需要明确指定我想打印哪个键……我不想一个一个列出来……

谢谢任何帮助或想法!如果需要我进一步解释或提供更多信息,请告诉我。

2 个回答

1

也许 pandas 可以做到这一点——但我从来没有尝试过读取 JSON 格式的数据。

import pandas as pd

df = pd.read_json( ... )

df.to_csv( ... )

pandas.DataFrame.to_csv

pandas.io.json.read_json


编辑:

data = ''' [
  {
    "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,
  }
]'''

import pandas as pd

df = pd.read_json(data)

print df

df.to_csv('results.csv')

结果:

   age             firstName            lastName nationality     nickname
0   24  Nicolas Alexis Julio  N'Koulou N'Doubena    Cameroon  N. N'Koulou
1   26     Alexandre Dimitri        Song-Billong    Cameroon      A. Song

使用 pandas,你可以把数据保存为 csv 格式、excel 表格等等(甚至可能直接保存到数据库里)。

而且你还可以对表格中的数据进行一些操作,并把结果以图表的形式展示出来。

1

你的 TypeError 错误是因为你试图用一个列表 list_of_attributes 来索引一个字典 x,也就是你写了 x[list_of_attributes]。这在 Python 中是不对的。在这种情况下,你正在遍历 readable_json,看起来每次遍历都会返回一个字典。其实你不需要从这些数据中提取值来写出它们。

DictWriter 应该能满足你的需求。

import csv
[...]

def encode_dict(d, out_encoding="utf8"):    
    '''Encode dictionary to desired encoding, assumes incoming data in unicode'''
    encoded_d = {}
    for k, v in d.iteritems():
        k = k.encode(out_encoding)
        v = unicode(v).encode(out_encoding)        
        encoded_d[k] = v
    return encoded_d

list_of_attributes = readable_json[0].keys()
# sort fields in desired order
list_of_attributes.sort()

with open('WCData_Rows.csv',"wb+") as csv_out:
    writer = csv.DictWriter(csv_out, fieldnames=list_of_attributes)
    writer.writeheader()
    for data in readable_json:
        writer.writerow(encode_dict(data))

注意: 这假设 readable_json 中的每个条目都有相同的字段。

撰写回答