Python将多个JSON对象解析为一个对象

时间:2017-04-17 17:55:30

标签: python json csv

我目前有一个看起来像这样的json文件....

{
    "data": [
    {
        "tag": "cashandequivalents",
        "value": 10027000000.0
    },
    { 
        "tag": "shortterminvestments",
        "value": 101000000.0
    },
    {
        "tag": "accountsreceivable",
        "value": 4635000000.0
    },
    {
        "tag": "netinventory",
        "value": 1386000000.0
    }...

但我想要的是这个

{ 
    "cashandequivalents": 10027000000.0, 
    "shortterminvestments":101000000.0 , 
    "accountsreceivable":4635000000.0,  
    "netinventory":1386000000.0
}

我只是不知道该怎么做。

也许有一种更简单的方法,但这对我来说似乎最合乎逻辑,因为下一步是writer.writerow到csv

所以最终csv看起来像

cashandequivalents | shortterminvestments | accountsreceivable | netinventory
100027000000         101000000000           46350000000          13860000000
###########          ############           ###########          ...........

writer.writeheader将在循环之外完成,所以我只写了值,而不是“标签”)

谢谢

2 个答案:

答案 0 :(得分:3)

天真的解决方案:

import json

json_data = {
    "data": [
        {
            "tag": "cashandequivalents",
            "value": 10027000000.0
        },
        {
            "tag": "shortterminvestments",
            "value": 101000000.0
        },
        {
            "tag": "accountsreceivable",
            "value": 4635000000.0
        },
        {
            "tag": "netinventory",
            "value": 1386000000.0
        }
    ]
}

result = dict()
for entry in json_data['data']:
    result[entry['tag']] = entry['value']

print json.dumps(result, indent=4)

<强>输出

{
    "shortterminvestments": 101000000.0, 
    "netinventory": 1386000000.0, 
    "accountsreceivable": 4635000000.0, 
    "cashandequivalents": 10027000000.0
}

答案 1 :(得分:1)

最简单,最干净的方法是使用词典理解。

d = {
 "data": [
  {
  "tag": "cashandequivalents",
  "value": 10027000000.0
  },
  { 
  "tag": "shortterminvestments",
  "value": 101000000.0
  },
  {
  "tag": "accountsreceivable",
  "value": 4635000000.0
   },
   {
   "tag": "netinventory",
   "value": 1386000000.0
   }
 ]
}
newDict = {i['tag']: i['value'] for i in d['data']}

# {'netinventory': 1386000000.0, 'shortterminvestments': 101000000.0, 'accountsreceivable': 4635000000.0, 'cashandequivalents': 10027000000.0}

这将遍历原始list的{​​{1}}项中包含的"data",并创建一个新内联键,其中每个键的值为dictionary并且迭代期间每个值为tag