如何将JSON转换为csv文件?

时间:2017-08-14 05:25:24

标签: python-3.x

在下面的JSON中,我需要将所有字段放在customer和address下作为列标题,然后是字段的所有值。

{
  "customer" : {
    "customerReferenceId" : "string",
    "customerName" : "string",
    "customerId" : "string",
    "lastFourTaxId" : "string",
    "primaryOfficerId" : "string",
    "primaryOfficerName" : "string"
  },
  "address" : {
    "addressType" : "string",
    "addressLine1" : "string",
    "addressLine2" : "string",
    "addressLine3" : "string",
    "addressLine4" : "string",
    "city" : "string",
    "stateCode" : "string",
    "postalCode" : "string",
    "countryCode" : "string",
    "countryName" : "string"
  }
}

我有以下代码对我有用,但这仅适用于客户,如何将字段放在地址以及标题下,然后将值放在它们下面。

import json
import csv

with open('c.json') as json_data:
      data = json.load(json_data)
      fo = open("CustomerSearch.csv","w")
      fo.write("CustomerId"+ "," + "CustomerName" + "," + 
              "CustomerReferenceId" + "," + "LastFourTaxId" + "," + 
              "PrimaryOfficerId" + "," + "PrimaryOfficerName")
      fo.write('\n')
      for r in data['customerData']:             
          fo.write(r ['customerId'] + "," + r['customerName'] + "," + 
                  r['customerReferenceId'] + "," + r['lastFourTaxId'] + "," 
                  + r['primaryOfficerId'] + "," + r['primaryOfficerName'])
          fo.write('\n')
      fo.close()    

0 个答案:

没有答案