0

I have a string:

str_rfrnc = '["text"]["title"]["res"]["din"]'

I load a json:

data = json.loads(myjson)

The below code works fine:

print(data["text"]["title"]["res"]["din"])

How to use the string for the same result as above?

print(data[str_rfrnc]) #This fails
0

2 Answers 2

1

This is the simplest solution that works:

>>> str_rfrnc = '["text"]["title"]["res"]["din"]'
>>> data = { 'text': { 'title': { 'res': { 'din': 10 } } } }
>>> eval('data' + str_rfrnc)
10

Note that you should use eval only if you trust the contents of str_rfrnc.

Sign up to request clarification or add additional context in comments.

Comments

0

This is a solution that doesn't use eval:

>>> from operator import getitem
>>> from functools import reduce
>>> from re import split

>>> str_rfrnc = '["text"]["title"]["res"]["din"]'
>>> data = { 'text': { 'title': { 'res': { 'din': 10 } } } }

>>> fields = split(r'[\[\]"]+', str_rfrnc)[1:-1]
>>> fields
['text', 'title', 'res', 'din']

>>> reduce(getitem, fields, data)
10

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.