是否可以使用诸如“['time']['updated']"之类的变量?解析JSON? [英] Is it possible to use a variable such as "['time']['updated']" to parse JSON?
本文介绍了是否可以使用诸如“['time']['updated']"之类的变量?解析JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好的,json_tree 是一个包含如下内容的变量:
Ok, json_tree is a variable that contains something that looks like this:
json_tree = "['time']['updated']"
你能把它作为一个变量传递......
Can you pass it as a variable....
hdr = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' }
req = urllib.request.Request(url, headers=hdr)
readdata = urllib.request.urlopen(req)
json_data = readdata.read()
json_dict = json.loads(json_data)
喜欢吗??
print(json_dict[json_tree])
我的目的是将 .ini 中的许多 json_tree 值之一传递到包含上述代码的类中.如果这是一个糟糕的计划,有什么可以替代的?
My purpose is to pass one of many json_tree values from a .ini into the class that contains the above code. If this is a bad plan, what could work, instead?
谢谢!
推荐答案
这是 jsonpath
,在该语法中,可以使用表达式 time.updated
来引用相关值.
This is a use case for jsonpath
, in which syntax one would use the expression time.updated
to refer to the value in question.
json_expr = "time.updated"
json_dict = {"time": {"updated": "2018-01-05"}}
from jsonpath_rw import parse as parse_jsonpath
results = parse_jsonpath(json_expr).find(json_dict)
if len(results) == 0:
raise Exception("Could not find any matches for %r in %r" % (json_expr, json_dict))
elif len(results) > 1:
raise Exception("Expression %r had more than one match; cannot use for configuration" % (json_expr,))
result = results[0].value
这篇关于是否可以使用诸如“['time']['updated']"之类的变量?解析JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文