Answer the question
In order to leave comments, you need to log in
How to substitute the path to an element from a string?
Hey!
There is a script that receives JSON and the path to the desired element as input,
for example:
path = "['fields']['components']['name']"
json = {'fields': {'components': {'id': '10437', 'name': 'Bug'}}}
print(json[path])
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
print(json[path])
KeyError: "['fields']['components']['name']"
Answer the question
In order to leave comments, you need to log in
path = "fields.components.name".split('.')
json = {'fields': {'components': {'id': '10437', 'name': 'Bug'}}}
for p in path:
json = json[p]
print(json)
import re
value = json
for key in re.findall("'(.*?)'", path):
value = value[key]
import re
from functools import reduce
value = reduce(lambda c, k: c[k], re.findall("'(.*?)'", path), json)
path = "['fields']['components']['name']"
json = {'fields': {'components': {'id': '10437', 'name': 'Bug'}}}
print (eval('json' + path + ''))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question