0

我必须找到一种方法来解析多个 json 文件并在 dict 中插入键值,其中 json 键作为 dict 变量。主要问题是 json 多对象总是不同的,所以我必须找到一种动态的方式来处理多个对象(就像下面显示的输入字段中的多个变量一样)。

下面是一个 json 文件的示例:

{
   "ver":2,
   "inputs":[
      {
     "sequence":4294967295,
     "witness":"",
     "prev_out":{
        "spent":true,
        "spending_outpoints":[
           {
              "tx_index":400037372,
              "n":0
           }
        ],
        "tx_index":321333092,
        "type":0,
        "addr":"3BMEXa8wC24GWaQ9HzrWmDywdhwE7yNPjL",
        "value":510000000,
        "n":0,
        "script":"a91469f375b807f9052b0d9cb5b5c19698e7e2c77b0887"
     },
     "script":"0047..."
  }
   ],
   "weight":2428,
   "block_height":555269,
   "relayed_by":"127.0.0.1",
   "out":[
      {
     "spent":true,
     "spending_outpoints":[
        {
           "tx_index":400098206,
           "n":142
        }
     ],
     "tx_index":400037372,
     "type":0,
     "addr":"1AcLPK6EHL5r26Ee2kCEgMxL394T4vo6Lu",
     "value":200000000,
     "n":0,
     "script":"76a9146967df4b117a2c7ec36302493939dffc5176aa3d88ac"
  },
  {
     "spent":true,
     "spending_outpoints":[
        {
           "tx_index":400305587,
           "n":0
        }
     ],
     "tx_index":400037372,
     "type":0,
     "addr":"3BMEXa8wC24GWaQ9HzrWmDywdhwE7yNPjL",
     "value":309800000,
     "n":1,
     "script":"a91469f375b807f9052b0d9cb5b5c19698e7e2c77b0887"
  }
   ],
   "lock_time":0,
   "size":607,
   "double_spend":false,
   "block_index":1737822,
   "time":1545656997,
   "tx_index":400037372,
   "vin_sz":1,
   "hash":"c2155d02b743c09c51eb37c4f86392f9b1dec552c549ba8e217885cd69aee2fa",
   "vout_sz":2
}

我已经尝试过这个:

dic = {}
dic = OrderedDict()
    try:
        dic['ver'] = data['ver']
        for doc in data['inputs']:
            dic['in_sequence{}'.format(i)] = doc['sequence']
            dic['in_witness{}'.format(i)] = doc['witness']
            dic['in_spent{}'.format(i)] = doc['prev_out']['spent']

等等...

但是每个循环都会生成新的变量名称,我必须避免这种情况。我怎样才能做到这一点?

4

1 回答 1

0

json模块为您处理创建键值对。尝试这个:

import json

with open('data.json', 'r') as fp:
  d = json.load(fp)

然后字典d包含对。例如获取'ver'键的值:

print(d['ver']) # 2
于 2018-12-29T21:51:15.987 回答