Reputation: 29
I already asked that question and read a lot of JSON extraction examples and still I cant handle with that JSON... :( I am trying to get only the 'addr_tag' data without anything else, I can get some other information easily but i dont know the right syntax to get the 'addr_tag'
Thanks!
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'...
Thanks!
Upvotes: 1
Views: 195
Reputation: 180401
It is deeply nested, txs
is the outer key, the value for txs
is a list which has a dict with the inputs
whose values is also a list that contains a dict, inside that dict prev_out
has a dict as a value that has the addr_tag
key:
print(obj1["txs"][0]["inputs"][0]["prev_out"]["addr_tag"])
There are actually 2 addr_tags
in the json the second is under:
print(obj1["txs"][0]["out"][1]["addr_tag"])
Satoshi Dice Change Address
If the keys are not always there you can use 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)
If any key is not in your json, the value will be None so you can just check with an if:
if k1 is not None:
.......
if k2 is not None:
................
Looking at the link the data and format keeps changing from run to run, this function will recursively check all the dicts and pull any "addr_tag"
values:
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")))
using the link json, you get which repeats some keys but you can call set(..
instead of list:
['Satoshi Dice Change Address', 'Satoshi Dice Change Address', 'SatoshiDICE 50%', 'Satoshi Dice Change Address']
Upvotes: 2