python - 如何通过密钥从 JSON 文件中获取项目?
问题描述
所以我有这个JSON
文件:
{
"test": {
"1.0.0": {
"by": "xpath",
"locator": "//div/span/a"
},
"1.0.1": {
"by": "xpath1",
"locator": "//div/span"
},
"1.0.2": {
"by": "xpath2",
"locator": "//div/span"
}
},
"test1": {
"1.0.1": {
"by": "id",
"locator": "add"
},
"1.0.2": {
"by": "id",
"locator": "/ADD"
}
},
"test2": {
"1.0.1": {
"by": "css",
"locator": "div span"
},
"1.0.2": {
"by": "css",
"locator": "div span a"
}
}
}
我想从需要名称和版本号的项目中获取 2 个键(by
和) :locator
test1
1.0.1
"test1": {
"1.0.1": {
"by": "id",
"locator": "add"
},
这是我尝试过的:
with open('file.json') as f:
json_file = load(f)
获取我的物品:
item = json_file.get('test1')
for x in item:
if x == `1.0.1`_:
print(item[x]['by'])
print(item[x]['locator'])
for
所以这很好用,但我想知道如何在没有这个循环的情况下将它放在一行中。
解决方案
按键索引怎么样?
import json
with open('file.json') as f:
json_file = json.load(f)
json_file["test1"]["1.0.1"]["by"]
json_file["test1"]["1.0.1"]["locator"]
try - except KeyError
如果键不存在,您可以将这些调用包装在 a中以捕获。或者,您可以在使用之前明确检查密钥是否存在。就像是:
if "1.0.1" in json_file["test1"]:
print(json_file["test1"]["1.0.1"]["by"])
print(json_file["test1"]["1.0.1"]["locator"])
您也可以使用dict.get
, 如果返回None
,则该键不存在。
version_info = json_file["test1"].get("1.0.1", None)
if version_info is not None: # exists
print(json_file["test1"]["1.0.1"]["by"])
print(json_file["test1"]["1.0.1"]["locator"])
推荐阅读
- database - mongo在多个字段的聚合查询中可以多次返回一个文档的原因是什么?
- python - 函数返回格式
- python - 子记录器的默认处理程序是什么?
- google-bigquery - 如何在不指定列名的情况下使用 bigquery 在表中的每一列上调用内置函数?
- python - 当我的公司电子邮件托管在 Google 上时,如何通过 python 脚本发送电子邮件
- java - 如何使用 Maven 与 JUnit5 标记
- bash - 如何使用可能有新行的输入每 n 个字符插入一个模式?
- android - 缩放 CalendarView 但适合边界
- javascript - 我们如何比较每个元素数组并根据值显示元素
- c++ - 使用 arm-fsl-linux-gnueabi-gcc 编译:int64_t 为 32 位长