首页 > 解决方案 > 从 Json Python 获取特定的字段值

问题描述

我有 JSON 作为响应,我正在尝试获取所有“Id”和“Pages”值并将它们放入数组(或列表)中以供后续步骤

[
{
    "Page": 1,
    "Content": [
        {"Id": 100000000000001,"Title": "title1", ...},
        {"Id": 100000000000002,"Title": "title2", ...},
        {"Id": 100000000000003,"Title": "title3", ...}
    ]
},
{
    "Page": 2,
    "Content": [
        {"Id": 100000000000004,"Title": "title4", ...},
        {"Id": 100000000000005,"Title": "title5", ...},
        {"Id": 100000000000006,"Title": "title6", ...}
    ]
},
{
    "Page": 3,
    "Content": [
        {"Id": 100000000000007,"Title": "title7", ...},
        {"Id": 100000000000008,"Title": "title8", ...},
        {"Id": 100000000000009,"Title": "title9", ...}
    ]
}

]

通过使用pages = [ e['Page'] for e in data ] 从这里获得“页面”值

无法获得“Id”值。试过了

for el in data: print (el['Content']['Id'])

但是出现错误TypeError: list indices must be integers or slices, not str

你能帮助我吗?

更新 1 :抱歉我的问题有点不正确:作为这个 JSON 的输出,我想返回数组 ["id1","id2",...,"id9"],而不是打印

标签: pythonarraysjsonlistdictionary

解决方案


使用列表理解,您可以轻松做到这一点

a = [
{
    "Page": 1,
    "Content": [
        {"Id": 100000000000001,"Title": "title1",  },
        {"Id": 100000000000002,"Title": "title2",  },
        {"Id": 100000000000003,"Title": "title3",  }
    ]
},
{
    "Page": 2,
    "Content": [
        {"Id": 100000000000004,"Title": "title4",  },
        {"Id": 100000000000005,"Title": "title5",  },
        {"Id": 100000000000006,"Title": "title6",  }
    ]
},
{
    "Page": 3,
    "Content": [
        {"Id": 100000000000007,"Title": "title7",  },
        {"Id": 100000000000008,"Title": "title8",  },
        {"Id": 100000000000009,"Title": "title9",  }
    ]
}

]

res = [[i['Page'],[ j['Id'] for j in i['Content']]] for i in a]
print(res)

输出

[[1, [100000000000001, 100000000000002, 100000000000003]],
 [2, [100000000000004, 100000000000005, 100000000000006]],
 [3, [100000000000007, 100000000000008, 100000000000009]]]

推荐阅读