Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.2k views
in Technique[技术] by (71.8m points)

Finding values in JSON type response (HTTP) in python

I have a json response

{"length": 2, "chain": [{"index": 0, "transactions": [], "timestamp": 0, "previous_hash": "0", "nonce": 0, "hash": "6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9"}, {"index"
: 1, "transactions": [{"test": "test2.m4a", "ipfs_hash": "QmaQgbSbgZdAfdiHmnfD9PevwpYSepytvA5G6agupqjVA3", "timestamp": 1610467381.102983, "Mac_ADD": "e0:94:67:bc:17:f9", "signature": "b'AQAgIQgAAD'"}], "timestamp":1610467386.9993732,"previous_hash":"6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9", "nonce": 214, "hash": "00a92715e60f577a57165b52c02e2b6bbef1ba60a3a27ead16e4d6a7a0a9d3d2"}], "peers": []}

I want to find the corresponding "ipfs_hash" using the "test" value. How do I achieve this in python?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As the others have mentioned, you can use json to load your string into a python object, e.g., a dictionary.

s = '''{"length": 2, "chain": [{"index": 0, "transactions": [], "timestamp": 0, "previous_hash": "0", "nonce": 0, "hash": "6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9"}, {"index"
: 1, "transactions": [{"test": "test2.m4a", "ipfs_hash": "QmaQgbSbgZdAfdiHmnfD9PevwpYSepytvA5G6agupqjVA3", "timestamp": 1610467381.102983, "Mac_ADD": "e0:94:67:bc:17:f9", "signature": "b'AQAgIQgAAD'"}], "timestamp":1610467386.9993732,"previous_hash":"6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9", "nonce": 214, "hash": "00a92715e60f577a57165b52c02e2b6bbef1ba60a3a27ead16e4d6a7a0a9d3d2"}], "peers": []}'''

import json

d = json.loads(s)

test = 'test2.m4a'
for c in d['chain']:
    for t in c['transactions']:
        if t['test'] == test:
            print(t['ipfs_hash'])


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...