python - 在变量中保存对 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]
因为它们可能并不总是按这个顺序
解决方案
您可以在 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 的更多信息。
推荐阅读
- android - "'value >= min && value <=max' : is not true " 即使值介于两者之间 :: Flutter
- reactjs - 如何使用反应开发服务器禁用 @typescript-eslint/no-unused-vars 规则
- ios - 如何在另一个 uiview 上使用 uiview 的 AutoLayout 约束?
- sql - 如何在 Oracle 中使用合并命令
- javascript - ava中的t.context范围
- ios - 如何在一定范围内向上拖动父 UIView 中的 UIContainer 视图?
- r - 改变列表中的每个元素以将其元素编号附加为新列
- java - 如何按升序对 ArrayList 的元素进行排序?- 爪哇
- database - 这两个kdb函数的目的是什么?
- asp.net - 如何在没有实体框架的 asp.net mvc 中创建分页