Is it possible to use a variable such as “['ti

2019-08-20 01:24发布

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)

like so??

    print(json_dict[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?

Thank you!

1条回答
冷血范
2楼-- · 2019-08-20 02:18

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
查看更多
登录 后发表回答