在python中使用jsonpickle来解析多个子属性

时间:2011-12-06 19:32:09

标签: python json parsing

我正在解析看起来像这样的JSON:

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

我如何使用jsonpickle获得第二个attr4的someattr?有点让我迷路了。提前谢谢。

1 个答案:

答案 0 :(得分:0)

  

我如何使用jsonpickle获得第二个attr4的someattr?

请注意,您的json对象在结束方括号之前有一个额外的逗号,这将使解析器失败。删除后,您可以:

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!