首页 > 解决方案 > 在 Python 3.0 中使用 json 对象数组(树结构中的嵌套数据/数据)按摩字典中的数据

问题描述

我需要将“地址”的值存储在一个变量中以供以后使用。“地址”值位于 json.dump 输出的深处。

从我收集到的一些类似问题来看,我需要在每个值之间迭代才能访问 ScriptPubKey (dict)。由于我对 Python 的了解只有几个小时,并且没有太多关于编程的先验知识,因此我确信我错过了一些简单的东西——或者完全误解了手头的任务。

    for x in response['result']['vout']:
    for y in x:
    print(y)

所以这是我遇到问题的程序的一部分:

###Function
def gettranshash(transhashen):
    payload = {
    "method": "getrawtransaction",
    "params": [transhashen],
    }
    response = requests.post(url, data=json.dumps(payload), headers=headers).json() 
    response = response['result']
    payload = {
    "method": "decoderawtransaction",
    "params": [response],
    }
    response = requests.post(url, data=json.dumps(payload), headers=headers).json()
    return response

###How I access the function in my program
        transaktionshash = input("write transactionhash for a block: ")
        response = gettranshash(transaktionshash)
        print("Blocket: ", response['result']['hash'])
###Missing the address output :(
        print("Blocket: ", response['result']['vout'])

响应结果:

{'result': {'txid': 
'4d879b24d65dd418a8e806ed69df7f170022e89666590a7b08e0095009865a5b', 
'hash': 
'4d879b24d65dd418a8e806ed69df7f170022e89666590a7b08e0095009865a5b', 
'version': 1, 'size': 87, 'vsize': 87, 'locktime': 0, 'vin': 
[{'coinbase': '0163', 'sequence': 4294967295}], 'vout': [{'value': 50.0, 
'n': 0, 'scriptPubKey': {'asm': 'OP_DUP OP_HASH160 
071e31b8289aa9d80b970230cb1b8b76466f2ec4 OP_EQUALVERIFY OP_CHECKSIG', 
'hex': '76a914071e31b8289aa9d80b970230cb1b8b76466f2ec488ac', 'reqSigs': 
1, 'type': 'pubkeyhash', 'addresses': 
['1eduGsrvBJcfyTMij2rYXk9viiVV78PNq']}}]}, 'error': None, 'id': None}

这是 response['result']['vout'] 的结果:

[{'value': 50.0, 'n': 0, 'scriptPubKey': {'asm': 'OP_DUP OP_HASH160 
071e31b8289aa9d80b970230cb1b8b76466f2ec4 OP_EQUALVERIFY OP_CHECKSIG', 
'hex': '76a914071e31b8289aa9d80b970230cb1b8b76466f2ec488ac', 'reqSigs': 
1, 
'type': 'pubkeyhash', 'addresses': 
['1eduGsrvBJcfyTMij2rYXk9viiVV78PNq']}}]

这是来自文档:

"vout" : [ (array of json objects) 
{ 
"value" : x.xxx, (numeric) The value in BTC 
"n" : n, (numeric) index 
"scriptPubKey" : { (json object) 
"asm" : "asm", (string) the asm 
"hex" : "hex", (string) the hex 
"reqSigs" : n, (numeric) The required sigs 
"type" : "pubkeyhash", (string) The type, eg 
'pubkeyhash' 
"addresses" : [ (json array of string) 
"address" (string) bitcoin address 
,... 
] 
} 
} 
,... 
], 

所以基本上; 我需要访问“地址”值,以便将其用作不同函数的迭代中的输入。

非常感谢任何潜在的提示,如果我需要添加其他信息或澄清任何事情,请告诉我:)

标签: pythonarraysjson

解决方案


推荐阅读