从JSON获取特定数据

时间:2015-12-05 20:38:19

标签: python json api python-3.x url

我已经问过这个问题并阅读了很多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'... 

谢谢!

1 个答案:

答案 0 :(得分:2)

它是嵌套的,txs是外键,txs的值是一个列表,其中包含inputs的字典,其值也是包含字典的列表,在dict prev_out里面有一个dict作为具有addr_tag键的值:

print(obj1["txs"][0]["inputs"][0]["prev_out"]["addr_tag"])

json中实际上有2 addr_tags,第二个是{{p>}

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:
      ................

查看链接数据和格式在运行之间不断变化,此函数将递归检查所有dicts并提取任何"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']