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?

Answer

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'])