将JSON数据写入CSV

时间:2019-08-06 14:01:50

标签: python json csv

我有一个动态json,根据记录,键(属性)会有所不同。

我想将以下json数据写入到csv文件中:

[{"Id": "12345",
  "attributes": {"Address": [{"label": "United Kingdom",
                              "value": {"AddressLine": [{"value": "Baker "
                                                                  "Street"}]}},
                             {"label": "United States",
                              "value": {"AddressLine": [{"value": "Florida"}]}}],
                 "CountryCode": [{"value": "Australia"}],
                 "Identifiers": [{"value": {"Type": [{"value": "Licence Id"}]}},
                                 {"value": {"Type": [{"value": "NPI"}]}}],
                 "StatusReasonCode": [{"value": "XXX"}],
                 "UniqueId": [{"value": "71581742"}]},
  "createdBy": "Rahul"}]

数据应采用以下csv格式:

ID, createdBy, CountryCode, StatusReasonCode, Identifiers, UniqueId, AddressLine
12345,Rahul,Australia,XXX,Licence Id,71581742,Baker Street
12345,Rahul,Australia,XXX,NPI,71581742,Florida

这是我的代码,用于从json中提取数据:

import json

with open('data.json') as f:
    data = json.load(f)

for key,value in data.items():

    if(type(value))==str:
        print(key + ',' + value)
    # global res
    res =[]
    if(type(value))==list:
        for fg in value:
            crosswalk_final=fg['value']
    if (type(value))== dict:
        for key1,val in value.items():
            for k in val:
                if type(k['value']) == dict:

                   for sub_key,sub_value in k.items():

                      if(type(sub_value)) == dict:
                          for child_key,child_value in sub_value.items():

                              if(type(child_value)) == list:
                                for m in child_value:

                                    if type(m['value']) == dict:
                                        for qaq,waq in m.items():

                                            if (isinstance(waq, dict)):
                                                for our,pur in waq.items():

                                                    for qq in pur:
                                                       print(our+','+qq['value'])

                                    else:
                                        pass
                                        print(key1+'_'+sub_key+'_'+child_key+','+m['value'])

                else:
                    attr1=(key+'_'+key1+','+k['value'])
                    print((attr1))

上面的代码给我以下格式的结果:

Id,12345
createdBy,Rahul
attributes_UniqueId,71581742
attributes_CountryCode,Australia
attributes_StatusReasonCode,XXX
Address_value_AddressLine,Baker Street
Address_value_AddressLine,Florida
Identifiers_value_Type,Licence Id
Identifiers_value_Type,NPI

但是我不确定如何在csv中编写它(与上面显示的格式相同)。

1 个答案:

答案 0 :(得分:-1)

编写一个将字典平整为具有恒定长度的列表的函数。如果缺少键,则将值设置为“无”。 示例:

data_dict = {"a": 1, "c": 12, "b": 0}
data_list = [data_dict.get("a"), data_dict.get("b"), data_dict.get("c")]

然后在csv中插入