使用Python将具有嵌套数组的JSON转换为CSV

时间:2018-10-11 09:27:53

标签: python json csv

这是我的JSON模板:

{
  "field 1": [
    {
      "id": "123456"
    },
    {
      "about": "YESH"
    },
    {
      "can_post": true
    },
    {
      "category": "Community"
    }
  ],
  "field 2": [
    {
      "id": "123456"
    },
    {
      "about": "YESH"
    },
    {
      "can_post": true
    },
    {
      "category": "Community"
    }
  ]
}

我想使用Python将这种JSON转换为以下格式的CSV:

0 field 1, id, about, can_post, category

1 field 2, id, about, can_post, category

我尝试使用熊猫先读取read_json,然后再读取to_csv,但这没有用。

谢谢

3 个答案:

答案 0 :(得分:1)

如果您有data之类的json,怎么办

data = [
   {
    "site": "field1",
    "id": "123456",
    "about": "YESH",
    "can_post": True,
    "category": "Community"
  },
  {
    "site": "field2",
    "id": "123456",
    "about": "YESH",
    "can_post": True,
    "category": "Community"
  }
]
# also use True instead of true

df = pd.DataFrame.from_dict(data)

print(df)
# use df.to_csv('filename.csv') for csv

输出:

  about  can_post   category      id    site
0  YESH      True  Community  123456  field1
1  YESH      True  Community  123456  field2

答案 1 :(得分:1)

这里的难点是,您的json初始结构不仅仅是一个映射列表,而是一个映射,其中值又是映射列表。

恕我直言,您必须预处理您的输入,或逐元素处理它,以获得可以转换为csv行的列表或映射。这是一个可能的解决方案:

  • 提取第一个元素的键并使用它们来构建DictWriter
  • 为每个元素构建一个映射并将其存储在DictWriter中

代码可能是:

import json
import csv

# read the json data
with open("input.json") as fd:
    data = json.load(fd)

# extract the field names (using 'field' for the key):
names = ['field']
for d in next(iter(data.values())):
    names.extend(d.keys())

# open the csv file as a DictWriter using those names
with open("output.csv", "w", newline='') as fd:
    wr = csv.DictWriter(fd, names)
    wr.writeheader()
    for field, vals in data.items():
        d['field'] = field
        for inner in vals:
            for k,v in inner.items():
                d[k] = v
        wr.writerow(d)

使用您的数据可以得出:

field,id,about,can_post,category
field 1,123456,YESH,True,Community
field 2,123456,YESH,True,Community

答案 2 :(得分:1)

import csv
import json

json.load(json_data)将json_data(json文档(txt /二进制文件))反序列化为python对象。

with open('jsn.txt','r') as json_data:
    json_dict = json.load(json_data)

由于您的字段名称(将用作字段名称的键)位于不同的字典中,因此我们必须遍历该字典并将其放入列表field_names中。

field_names = [ 'field']
for d in json_dict['field 1']:
    field_names.extend(d.keys())

with open('mycsvfile.csv', 'w') as f:  
    w = csv.DictWriter(f, fieldnames = fieild_names)
    w.writeheader()

    for k1, arr_v in json_dict.items():
        temp = {k2:v for d in arr_v for k2,v in d.items()}
        temp['field'] = k1
        w.writerow(temp)


 输出

field,id,about,can_post,category
field 1,123456,YESH,True,Community
field 2,123456,YESH,True,Community


如果您发现上面的dict理解混乱

      k1  : arr_v 
'field 1' = [{ "id": "123456" },...{"category": "Community"}]

            for d in arr_v:                 
                        k2 : v
               d --> { "id": "123456" }