gpt4 book ai didi

python - Python 的 jsonpath_rw : How to navigate relatively?

转载 作者:太空宇宙 更新时间:2023-11-04 03:26:49 25 4
gpt4 key购买 nike

我有一个存储在 json 文件中的配置数据库。该文件从磁盘读取,由 Python 的 json 库解析并存储在名为 json 的变量中。

现在我正在研究 jsonpath_rw 以构建更具可读性的路径表达式,然后编写纯 Python 代码来访问多个嵌套的字典和数组。

这是我当前的代码:

# select all UART device serial numbers
exprSerial = parse('FPGAList.[*].UART.Serial')

#for serial in UART serial list
for match in exprSerial.find(json):
print("Match: " + match.value + " Path:" + str(match.full_path))

if (match.value == USBSerial):
#exprUART = match.full_path.Descendants) #under construction

第一个表达式列出了所有 UART 设备序列号。结果显示在屏幕上并正在运行。关于在线文档,我可以通过访问match.full_path 打印出匹配对象的完整路径。这是一个 jsonpath 对象。如果我对其调用 str(..),它会转换为可读字符串。

接下来,我的代码将值与给定的序列号进行比较。如果是真的,我想检查一些其他参数以确保安全:例如USBDeviceVendor。此 key 也存储在同一层次结构级别的 json 文件中。

我的目标是构建一个相对于 match.full_path 的新 jsonpath 以访问 USBDeviceVendor

错误的解决方案: exprVendor = parse(str(match.full_path) + "..USBDeviceVendor")

是否可以像 match.full_path.relative("..USBDeviceVendor") 一样扩展 match.full_path

最佳答案

如果你想上一层然后再下一层。而不是寻找当前结果的匹配后代。

使用`parent`:

parse('`parent`.USBDeviceVendor').find(match)

考虑:

>>> import jsonpath_rw as jp
>>> obj = {'y':{'x':1,'g':{'t':0}}}
>>> jp.parse('`parent`.g').find(jp.parse("y.x").find(obj)[0])[0].value
{'t': 0}

否则:

parse("`this`..USBDeviceVendor").find(match)

考虑:

>>> import jsonpath_rw as jp
>>> obj = {'y':{'x':{'g':{'t':0}}}}
>>> jp.parse("`this`..t").find(jp.parse("y.x").find(obj)[0])[0].value
0

关于python - Python 的 jsonpath_rw : How to navigate relatively?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32713573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com