将json文件映射到CSV行

时间:2016-10-20 00:28:22

标签: python json mapping

我正在尝试使用python进行一些类型转换。我以为我会使用标题名称字典来表示函数,并将这些函数映射到每个CSV行。

  'page':'ProductPage'
  'OAM':'False'
  'storeNum':'029'
  'brand':'Opti-UPS'
  'productPrice':'114.99'
 'SKU':'349829'
 'productID':'405220'
 'mpn':'GS1100B'
 'ean':'766908091211'
  'category':'UPS Systems'
 'isMobile':'False'

'page':'ProductPage'
  'OAM':'False'
  'storeNum':'029'
  'brand':'Aven'
  'productPrice':'2.99'
 'SKU':'563197'
 'productID':'442744'
 'mpn':'17551LF'
 'ean':'766955340416'
  'category':'Soldering
 'isMobile':'False'

现在想把这个列表写入csv,看起来像在MS Excel中,如下所示 -

Output

提前致谢。

1 个答案:

答案 0 :(得分:0)

假设您的JSON输入如下所示:

[{  "page":"ProductPage",
  "OAM":"False",
  "storeNum":"029",
  "brand":"Opti-UPS",
  "productPrice":"114.99",
 "SKU":"349829",
 "productID":"405220",
 "mpn":"GS1100B",
 "ean":"766908091211",
  "category":"UPS Systems",
 "isMobile":"False"},

{"page":"ProductPage",
  "OAM":"False",
  "storeNum":"029",
  "brand":"Aven",
  "productPrice":"2.99",
 "SKU":"563197",
 "productID":"442744",
 "mpn":"17551LF",
 "ean":"766955340416",
 "category":"Soldering",
 "isMobile":"False"}]

然后这个程序可能会做你想要的:

import json
import csv

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

headers = set().union(*data)

with open('out.csv', 'w') as result:
    result = csv.DictWriter(result, sorted(headers))
    result.writeheader()
    result.writerows(data)