简体   繁体   中英

Using jsonpickle in python to parse multiple child attributes

I'm parsing JSON that looks like this:

{
    "attr1": true,
    "attr2": "foo",
    "attr3": 7,
    "attr4": [
        {
        "someattr1": "foo",
        "someattr2": "bar"
        },
        {
        "someattr1": "foo",
        "someattr2": "bar"
        },
        ],
    "attr6": false
}

How would I go about getting the 2nd attr4's someattr1 using jsonpickle? Kinda got me lost. Thanks in advance.

How would I go about getting the 2nd attr4's someattr1 using jsonpickle?

Please note that your json object has an extra comma before the closing square bracket that will make the parser fail. Once removed that, you can:

import jsonpickle as jp

json = '''
{
    "attr1": true,
    "attr2": "fooA",
    "attr3": 7,
    "attr4": [
        {
        "someattr1": "fooB",
        "someattr2": "barC"
        },
        {
        "someattr1": "fooD",
        "someattr2": "barE"
        }
        ],
    "attr6": false
} '''

print jp.decode(json)['attr4'][1]['someattr1']  #index == 1 → 2nd in the series!!

HTH!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM