首页 > 解决方案 > 如何通过密钥从 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和) :locatortest11.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所以这很好用,但我想知道如何在没有这个循环的情况下将它放在一行中。

标签: pythonjson

解决方案


按键索引怎么样?

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"])

推荐阅读