E
E
Elvis2018-04-24 11:30:01
Python
Elvis, 2018-04-24 11:30:01

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'}}}

then if you call such code, it does not work
print(json[path])
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    print(json[path])
KeyError: "['fields']['components']['name']"

the path itself is not known until it comes to the script. how to make that it was possible to pull out on the way value?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2018-04-24
@Dr_Elvis

path = "fields.components.name".split('.')
json = {'fields': {'components': {'id': '10437', 'name': 'Bug'}}}

for p in path:
    json = json[p]
print(json)

S
Sergey Gornostaev, 2018-04-24
@sergey-gornostaev

import re

value = json
for key in re.findall("'(.*?)'", path):
    value = value[key]

or
import re
from functools import reduce

value = reduce(lambda c, k: c[k], re.findall("'(.*?)'", path), json)

V
Vitaly Arkhipov, 2018-04-24
@arvitaly

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 question

Ask a Question

731 491 924 answers to any question