Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.6 - Parse json response with dict inside dict

I'm being driven insane because I can't parse this json response. I've tried many different things and nothing works properly... Could you help me? The this is the file I am parsing:

{
    "info": {
        "funds": {
            "asset": {
                "net": "12516.000",
                "total": "0"
            },
            "borrow": {
                "btc": "0",
                "cny": "0",
                "ltc": "0"
            },
            "free": {
                "btc": "0",
                "cny": "0",
                "ltc": "0",
                "eth": "0"
            },
            "freezed": {
                "btc": "0",
                "cny": "0",
                "ltc": "0",
                "eth": "0"

            },
            "union_fund": {
                "btc": "0",
                "ltc": "0"
            }
        }
    },
    "result": true
}

I just want something like:

#What I want to get the "net" which is "12516.000", so I tried this:
funds = response['info']['funds']['asset']['net']

funds = response[0] returns { as answer, and funds = response[1] gives me r as a response, and finally if I try funds = response['info'] I get this type error: TypeError: string indices must be integers

like image 866
Vitor Alves Avatar asked May 13 '26 01:05

Vitor Alves


1 Answers

You haven't actually parsed the JSON, it's just being read as a string, so response[0] returns the first character of the JSON string, or {. To parse the JSON string,

import json
json.loads(response)['info']['funds']['asset']['net']

which is the pattern you're expecting. More details about the json library can be found here.

like image 66
kevmo314 Avatar answered May 15 '26 14:05

kevmo314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!