python - 如何遍历 JSON 数组并获取本身是 JSON 对象的键的值
问题描述
我一直在尝试做一些简单但对我来说很难解决的事情!
我有一个看起来像这样的 json 对象:
jsonObject = {
'attributes': {
'192': { <--- This can be changed times to times meaning different number
'id': '192',
'code': 'hello',
'label': 'world',
'options': [
{
'id': '211',
'label': '5'
},
{
'id': '1202',
'label': '8.5'
},
{
'id': '54',
'label': '9'
},
{
'id': '1203',
'label': '9.5'
},
{
'id': '58',
'label': '10'
}
]
}
},
'template': '12345',
'basePrice': '51233',
'oldPrice': '51212',
'productId': 'hello',
}
我想要做的是从选项中获取值(将 id 和标签都保存到列表中)
现在我只能做到:
for att, value in jsonObject.items():
print(f"{att} - {value}"
如何获取标签和 ID?
解决方案
您可以尝试以下代码:
attr = jsonObject['attributes']
temp = list(attr.values())[0] # It is same as "temp = attr['192']", but you said '192' can be changed.
options = temp['options']
for option in options:
print(f"id: {option['id']}, label: {option['label']}")
推荐阅读
- javascript - 反应本机函数返回未定义
- angular - 如何将 Angular ngFor 与 Observable 一起使用
- spring - Spring 引起:org.springframework.core.serializer.support.SerializationFailedException:无法反序列化有效负载?集群模式
- javascript - 如何使它在我选择错误答案时弹出“重试”按钮
- git - 无法将我的 git 存储库连接到 Jenkins
- architecture - 微服务架构 - 每个服务是否需要 API
- javascript - 如何在 React 项目中正确使用/导入 JavaScript 文件?
- java - CompletableFuture:在抛出异常之前获取对象
- angular - VS Code - Angular:对装饰器的实验性支持警告
- typescript - TypeScript 在 VS Code 中有哪些内置代码片段?