将json嵌套字典复制到csv fi

2024-05-12 18:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将以下json嵌套字典从api复制到csv文件

{
 "result": [{
               "short_description": "I am getting bluescreen error",
               "sys_id": "39b5f8c2376ede007520021a54990e5c",
               "opened_at": "2016-04-04 05:19:53",
               "number":"INC0258523"
             },
             {
               "short_description": "laptop crashed with a blue screen",
               "sys_id": "da0095380f43d200a4f941fce1050eeb",
               "opened_at":"2016-04-25 06:33:52",
               "number":"INC0259067"
             }, 
             {
               "short_description": "Laptop not booting",
               "sys_id": "ecf9c9b00f43d200a4f941fce1050e17",
               "opened_at": "2016-04-25 06:07:16",
               "number": "INC0259061"
             }]
}

到目前为止我已经试过了

^{pr2}$

我在csv文件的单个单元格中得到以下结果

[{"short_description":"I am getting bluescreen error","sys_id":"39b5f8c2376ede007520021a54990e5c","opened_at":"2016-04-04 05:19:53","number":"INC0258523"},{"short_description":"laptop crashed with a blue screen","sys_id":"da0095380f43d200a4f941fce1050eeb","opened_at":"2016-04-25 06:33:52","number":"INC0259067"},{"short_description":"Laptop not booting","sys_id":"ecf9c9b00f43d200a4f941fce1050e17","opened_at":"2016-04-25 06:07:16","number":"INC0259061"}]}

但是我需要它的格式,其中keys short_description,sys_id,opened_at,number是列名,它们的值作为相应的列数据。在


Tags: 文件csvidnumbersyserrordescriptionam
1条回答
网友
1楼 · 发布于 2024-05-12 18:15:59

您需要提取行字典。现在您正在使用顶层的'result'dict来为csv编写器提供数据。在

  with open('D:/file.csv', 'wb') as f:  
        w = csv.DictWriter(f, data['result'][0].keys())   
        for row in data['result']:
            w.writerow(row)

相关问题 更多 >