对CSV的API嵌套JSON响应

2024-09-28 20:56:35 发布

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

我正在尝试将嵌套的JSON响应转换为CSV。下面是JSON响应

{
"rows": [
[
{
"postId": 188365573,
"messageId": 198365562,
"accountId": 214,
"messageType": 2,
"channelType": "TWITTER",
"accountType": "TWITTER",
"taxonomy": {
  "campaignId": "2521_4",
  "clientCustomProperties": {
    "PromotionChannelAbbreviation": [
      "3tw"
    ],
    "PromotionChannels": [
      "Twitter"
    ],
    "ContentOwner": [
      "Audit"
    ],
    "Location": [
      "us"
    ],
    "Sub_Category": [
      "dbriefs"
    ],
    "ContentOwnerAbbreviation": [
      "aud"
    ],
    "PrimaryPurpose_Outcome": [
      "Engagement"
    ],
    "PrimaryPurposeOutcomeAbbv": [
      "eng"
    ]
  },
  "partnerCustomProperties": {},
  "tags": [],
  "urlShortnerDomain": "2721_spr.ly"
},
"approval": {
  "approvalOption": "NONE",
  "comment": ""
},
"status": "SENT",
"createdDate": 1433331585000,
"scheduleDate": 1435783440000,
"version": 4,
"deleted": false,
"publishedDate": 1435783441000,
"statusID": "6163465412728176",
"permalink": "https://twitter.com/Acctg/status/916346541272498176",
"additional": {
  "links": []
  }
 },
 0
 ],
[
{
"postId": 999145171,
"messageId": 109145169,
"accountId": 21388,
"messageType": 2,
"channelType": "TWITTER",
"accountType": "TWITTER",
"taxonomy": {
  "campaignId": "2521_4",
  "clientCustomProperties": {
    "PromotionChannelAbbreviation": [
      "3tw"
    ],
    "Eminence_Registry_Number": [
      "1000159"
    ],
    "PromotionChannels": [
      "Twitter"
    ],
    "ContentOwner": [
      "Ctr. Health Solutions"
    ],
    "Location": [
      "us"
    ],
    "Sub_Category": [
      "fraud"
    ],
    "ContentOwnerAbbreviation": [
      "chs"
    ],
    "PrimaryPurpose_Outcome": [
      "Awareness"
    ],
    "PrimaryPurposeOutcomeAbbv": [
      "awa"
    ]
  },
  "partnerCustomProperties": {},
  "tags": [],
  "urlShortnerDomain": "2521_spr.ly"
},
"approval": {
  "approvalOption": "NONE",
  "comment": ""
},
"status": "SENT",
"createdDate": 1434983660000,
"scheduleDate": 1435753800000,
"version": 4,
"deleted": false,
"publishedDate": 1435753801000,
"statusID": "616222222198407168",
"permalink": "https://twitter.com/Health/status/6162222221984070968",
"additional": {
  "links": []
}
},
 0
]   
}

我用来掩盖这一点的python代码是

import json
import csv 

# importing the data 
with open('Post_Insights_test.json') as Test:
data1 = json.load(Test)

# opening the csv 
csvdata= open('Data_table2.csv', 'w')
csvwriter = csv.writer(csvdata, delimiter=',')

#Taking the keys out from 1st dict, that too which aren't nested
header= data1["rows"][1][0].keys()
csvwriter.writerow(header)

for i in range(0,70):
  csvwriter.writerow(data1["rows"][i][0].values())

csvdata.close()

问题如下:

  1. 无法获取嵌套响应(如分类法)的键
  2. 无法获取嵌套响应(如分类法)的值
  3. 许多响应都有不同的头/键,因此理想情况下,我应该在excel中将它们作为头,但我不知道如何在python中这样做
  4. 我的excel表格显示了每个条目后的行间距,我不知道为什么

请帮忙。欢迎所有批评。谨致问候


Tags: csvthejsonstatustwitterrowscsvwriterdata1