我已经问过这个问题并阅读了许多JSON提取示例,但我仍然无法处理该JSON ... :(我试图仅获取'addr_tag'数据,而没有其他任何信息,我可以轻松获取其他一些信息,但是我不知道正确的语法来获取“ addr_tag”
谢谢!
import json
from urllib.request import urlopen
js1 = urlopen("https://blockchain.info/address/1dice97ECuByXAvqXpaYzSaQuPVvrtmz6?format=json&limit=1").read().decode('utf8')
obj1 = json.loads(js1)
print (obj1['txs']) #I need to know the what to put here instead of 'txs'...
谢谢!
它深深嵌套,txs
是外键,该值txs
是有一个字典的列表,inputs
其值也是包含的字典,里面那个字典列表prev_out
具有字典作为具有价值addr_tag
的关键:
print(obj1["txs"][0]["inputs"][0]["prev_out"]["addr_tag"])
addr_tags
json中实际上有2个,第二个在下面:
print(obj1["txs"][0]["out"][1]["addr_tag"])
Satoshi Dice Change Address
如果键不总是存在,则可以使用dict.get:
inter = js["txs"][0]
k1 = next((d["prev_out"].get("addr_tag") for d in inter["inputs"] if "prev_out" in d), None)
k2 = next((d.get("addr_tag") for d in inter["out"] if "addr_tag" in d), None)
如果您的json中没有任何密钥,则该值将为None,因此您可以使用if进行检查:
if k1 is not None:
.......
if k2 is not None:
................
查看链接,数据和格式会随着运行而不断变化,此函数将递归检查所有dict并提取所有"addr_tag"
值:
def rec_get(d, k):
if isinstance(d, dict):
if k in d:
yield d[k]
else:
for v in d.values():
yield from rec_get(v, k)
elif isinstance(d, list):
for v in d:
yield from rec_get(v, k)
print(list(rec_get(js, "addr_tag")))
使用链接json,您可以得到重复了一些键但可以调用set(..
而不是列表的方法:
['Satoshi Dice Change Address', 'Satoshi Dice Change Address', 'SatoshiDICE 50%', 'Satoshi Dice Change Address']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句