API嵌套JSON响应CSV

时间:2016-01-25 15:18:48

标签: python json csv pandas

我正在尝试将嵌套的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. 无法获取嵌套响应的密钥,例如taxonomy
  2. 无法获取嵌套响应的值,例如taxonomy
  3. 很多回复都有不同的标题/键,所以理想情况下我应该将它们作为我的Excel中的标题,但我无法弄清楚如何在python中执行此操作
  4. 我的excel表显示每次进入后的行间隙,我不知道为什么
  5. 请帮忙。所有批评都是受欢迎的。亲切的问候

0 个答案:

没有答案