使用可变键解析 JSON 对象
Parse JSON object with variable keys
我必须解析 JSON 个包含两个键的对象,这两个键在每个对象中可能不同。在下面的示例中,它是 "path/to/file"
和加入 "ecs2345.ms067"
.
我需要检查两个对象并评估 "ok"
和 "version"
的值。
我发现的所有示例都需要一个已定义的键。
解析器是 Python 或 Postgres jsonb。如果可以使用 JSON 路径,我特别感兴趣。
谢谢!
{
"path/to/file": [
{
"ecs2345.ms067": {
"error_type": "__prevalidation__",
"errors": [
"missing : origin_sample_ontology_curie"
],
"ok": false,
"version": "2.0"
}
},
{
"ecs2345.ms067": {
"errors": [],
"ok": true,
"version": "1.0"
}
}
]
}
使用json.loads
将整个东西转换为字典,然后遍历字典:
json_dict = json.loads(json_string)
for filename, file_data in json_dict.items():
for obj in file_data:
ok = obj["ok"]
version = obj["version"]
# do stuff with the variables.
# if you need the file name, it is filename variable.
我必须解析 JSON 个包含两个键的对象,这两个键在每个对象中可能不同。在下面的示例中,它是 "path/to/file"
和加入 "ecs2345.ms067"
.
我需要检查两个对象并评估 "ok"
和 "version"
的值。
我发现的所有示例都需要一个已定义的键。
解析器是 Python 或 Postgres jsonb。如果可以使用 JSON 路径,我特别感兴趣。
谢谢!
{
"path/to/file": [
{
"ecs2345.ms067": {
"error_type": "__prevalidation__",
"errors": [
"missing : origin_sample_ontology_curie"
],
"ok": false,
"version": "2.0"
}
},
{
"ecs2345.ms067": {
"errors": [],
"ok": true,
"version": "1.0"
}
}
]
}
使用json.loads
将整个东西转换为字典,然后遍历字典:
json_dict = json.loads(json_string)
for filename, file_data in json_dict.items():
for obj in file_data:
ok = obj["ok"]
version = obj["version"]
# do stuff with the variables.
# if you need the file name, it is filename variable.