【问题标题】:Is it possible to retrieve a JSON path from a variable in python?是否可以从 python 中的变量中检索 JSON 路径?
【发布时间】:2022-01-07 17:36:57
【问题描述】:

我正在编写一个程序来查询一个响应 JSON 对象的 API。 JSON 对象是多级的,包含多个数组和键值对。我想从每个响应中检索相当多的项目,并且为每个函数多次输入每个路径被证明是耗时且混乱的。

我想将每个 JSON 路径存储在字典中以进行迭代。我正在尝试完成的一个简单示例:

api_response = api_request(query)

paths_to_data = {}

paths_to_data["author"] = "['Items'][0]['AttributeSets'][0]['Author']"
paths_to_data["actor"] = "['Items'][0]['AttributeSets'][0]['Actor']"
paths_to_data["format"] = "['Items'][0]['AttributeSets'][0]['Format']"

cleaned_response = {}

for a in paths_to_data.keys():
    cleaned_response[a] = api_response.paths_to_data[a]

【问题讨论】:

    标签: python json python-3.x syntax


    【解决方案1】:

    由于您对路径进行硬编码,因此使用eval 应该是安全的。

    cleaned_response[a] = eval(f"api_response{paths_to_data[a]}")
    

    对于这样的事情,我通常会使用jq,除非它必须在 Python 中实现,在这种情况下你可以寻找一些 JSONPath 库。我对任何 JSONPath 库都不太熟悉,所以我不能推荐任何库,但我之前对 XML 使用过类似的东西。

    【讨论】:

      【解决方案2】:

      不要使用字符串。使用函数

      extractors = {}
      
      extractors["author"] = lambda d: d['Items'][0]['AttributeSets'][0]['Author']
      extractors["actor"] = lambda d: d['Items'][0]['AttributeSets'][0]['Actor']
      extractors["format"] = lambda d: d['Items'][0]['AttributeSets'][0]['Format']
      
      cleaned_data = {}
      
      for item, extractor in paths_to_data:
          cleaned_response[item] = extractor(api_response)
      

      【讨论】:

        猜你喜欢
        • 2018-05-11
        • 1970-01-01
        • 1970-01-01
        • 2019-02-25
        • 1970-01-01
        • 2011-09-23
        • 1970-01-01
        • 2017-09-18
        • 1970-01-01
        相关资源
        最近更新 更多