python - 仅在遍历 json 数据时获取字符串
问题描述
JSON:
{
"status": "success",
"data": {
"9": {
"1695056": {
"id": "1695056",
[...]
},
"csevents": {
"2807": {
"id": "2807",
"startdate": "2019-01-24 18:45:00",
"service_texts": [],
"eventTemplate": "1"
},
"2810": {
"id": "2810",
"startdate": "2019-01-31 18:45:00",
"service_texts": [],
"eventTemplate": "1"
}
}
},
"1695309": {
"id": "1695309",
[...]
},
"csevents": {
"3601": {
"id": "3601",
"startdate": "2019-05-17 18:45:00",
"service_texts": [],
"eventTemplate": "1"
}
我尝试使用python从“csevents”(“2807”,“2810”,3601“)中获取成员。问题是我在编码时不知道“9”(“1695056”,“1695309”)中的ID .
所以我尝试遍历“9”,然后遍历“csevents”,但如果我遍历“9”,我只会得到一个字符串,所以我不能再遍历“csevents”。
Python:
for whatever in json_object['data']['9']:
for id in whatever['csevents']:
print(id)
所以这行不通。有人知道我该如何解决吗?
谢谢
解决方案
必须清理您的 JSON 字符串才能使其正常工作,但查看您的解决方案似乎是您直接从您的dict
,您应该使用的是.items()
或.values()
:
for key, value in json_object['data']['9'].items():
# We can use .keys() here since we only need the IDs from csevents
csevent_keys = list(value['csevents'].keys())
print(csevent_keys)
# Output
['2807', '2810']
['3601']
推荐阅读
- javascript - Angular 9:与对象数组进行分叉连接
- python - 如何使用pymysql,KEY ERROR在python中连接mysql数据库
- javascript - HTTP 响应在浏览器中是乱码,但在 cURL 或 node.js 中符合预期
- c# - 如何禁用 Debugger.Launch(); 上的中断?
- sql - 如何按日期将查询结果导出到多个 csv 文件中?(微软 SQL 服务器)
- jinja2 - 函数中的 Jinja 变量
- vue.js - [Vue 警告]:无法解析组件:
- c++ - 带有 NuGet 包的 LNK1104:DirectXTKAudioWin8.lib
- android - supportFragmentManager 在片段中不起作用
- excel - 是否可以使用 Mac 在 VBA XL 中创建特定于工作表的命名范围