首页 > 解决方案 > 在变量中保存对 python 字典(来自 json 文件)项的引用

问题描述

我正在尝试将引用保存到无法保证项目订单的 json 文件中的值。到目前为止,我拥有这样一个数据集:

"Values": [
  {
    "Object": "DFC_Asset_05",
    "Properties": [
      {
        "Property": "WeightKilograms",
        "Value Offset": 5
      },
      {
        "Property": "WeightPounds",
        "Value Offset": 10
      }
    ]
  },
  {
    "Object": "DFC_Asset_05",
    "Properties": [
      {
        "Property": "Name",
        "Value Offset": 25
      },
      {
        "Property": "ShortName",
        "Value Offset": 119
      }
    ]
  }
]

并检索此对象:

{
  "Property": "ShortName",
  "Value Offset": 119
}

是这样的字符串:

reference = "[Object=DFC_Asset_06][Properties][Property=Name]"

这在字符串中看起来不错且易于理解,但是找到引用的值是非常不干净的,因为我必须首先使用正则表达式解析引用,然后在数据中循环以检索匹配项。

我做错了吗?有一个更好的方法吗?我查看了该reduce()函数,但它似乎是为带有静态数据的字典而设计的。例如,我无法保存直接键:

reference = "[1][Properties][1]"
reference_using_reduce = [1, "Properties", 1]

因为它们可能并不总是按这个顺序

标签: pythonjsonpython-3.xdictionary

解决方案


您可以在 JSON 上运行“查询”,而无需使用该pyjq模块引用特定索引:

query = (
    '.Values[]'  # On all the items in "Values"
    '|select(."Object" == "DFC_Asset_06")'  # Find key "Object" which holds this value
    '|."Properties"[]'  # And get all the items of "Properties"
    '|select(."Property" == "Name")'  # Where the key "Property" holds the value "Name" 
)
pyjq.first(query, d)

结果:

{'Property': 'Name', 'Value Offset': 25}

您可以在文档中阅读有关 jq 的更多信息。


推荐阅读