Python JSON通过字符串路径获取值
我有一个 JSON 文件,我想自动检查特定值, 就像: myJSON['generic']['lessgeneric']['store'] 应该等于 100
,
我正在考虑做这样的事情:
checks = [
{'name':'field_1','path':'myJSON['generic']['lessgeneric']['store']','value':'100'}
]
我没有提示如何将字符串 "myJSON['generic']['lessgeneric']['store']"
转换为其值。
编辑: 我是怎么解决的
path = "generic>lessgeneric>store"
value = 100
def check_value(path,value):
temp_json = my_json
for key in path.split(">"):
temp_json = temp_json[key]
if temp_json == value:
pass
I have a JSON file that I want to automatically check specific values,
like: myJSON['generic']['lessgeneric']['store']
should be equal to 100
,
I was thinking of doing something like this:
checks = [
{'name':'field_1','path':'myJSON['generic']['lessgeneric']['store']','value':'100'}
]
I have no clue how to convert the string "myJSON['generic']['lessgeneric']['store']"
into it's value.
edit:
how I solved it
path = "generic>lessgeneric>store"
value = 100
def check_value(path,value):
temp_json = my_json
for key in path.split(">"):
temp_json = temp_json[key]
if temp_json == value:
pass
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议您将其存储为列表或分隔字符串,而不是像这样存储路径。例如:
然后,您可以使用
str.split()
拆分path
键的值,并深入到您的对象。下面的递归函数接受一个对象(我们希望它是一个字典)和一个包含所有要深入研究的键的列表,并返回最终键处的值:然后,执行:
这假设您已经解析了 json使用
json
模块将其转换为myJSON
变量中的对象。Instead of storing the path like that, I suggest you store it as a list or as a delimited string. For example:
Then, you can split the value of the
path
key withstr.split()
, and drill down into your object. The following recursive function takes an object (that we expect to be a dictionary) and a list containing all the keys to drill down into, and returns the value at the final key:Then, do:
This assumes you've already parsed your json into an object in the
myJSON
variable using thejson
module.