python - 从 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"],而不是打印
解决方案
使用列表理解,您可以轻松做到这一点
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]]]
推荐阅读
- google-sheets - 在 Google 表格中获得最低价格
- flutter - 如何在 Flutter ListTile 中设置前导和标题之间的填充?
- pytorch - 练习基本的pytorch数据加载器时遇到TypeError:object()没有参数
- c - 获取线程 1:Xcode 中的 EXC_BAD_ACCESS (code=1, address=0x0)
- node.js - socket.io 服务器无法在网络外工作
- c++ - 有没有办法在 Qt 项目中添加一次性运行窗口?
- spring-boot - MockRestServiceServer 在测试中没有被调用
- haskell - 作为来自不同模块的数据构造函数的模式匹配
- javascript - 在具有不同值的对象数组中查找对象的最有效方法是什么?
- c - 如何自动将预处理器放入C中