0% found this document useful (0 votes)
1 views

find-a-value-within-nested-json-dictionary-in-python

The document discusses how to extract a specific value ('TEXT') from a nested JSON dictionary in Python, where one of the keys ('unknown') can vary. It provides code examples demonstrating how to access the value using both fixed keys and dynamic keys. Additionally, it suggests using a recursive function to navigate through the JSON structure if the key names are not known in advance.

Uploaded by

Pawan kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

find-a-value-within-nested-json-dictionary-in-python

The document discusses how to extract a specific value ('TEXT') from a nested JSON dictionary in Python, where one of the keys ('unknown') can vary. It provides code examples demonstrating how to access the value using both fixed keys and dynamic keys. Additionally, it suggests using a recursive function to navigate through the JSON structure if the key names are not known in advance.

Uploaded by

Pawan kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Find a value within nested json dictionary in python - Stack Overflow https://stackoverflow.com/questions/14227561/find-a-value-within-nested...

Find a value within nested json dictionary in python


Asked 7 years, 7 months ago Active 5 years, 9 months ago Viewed 52k times

From the following json, in python, I'd like to extract the value "TEXT". All the keys are constant
except for unknown. Unknown could be any string like "a6784t66" or "hobvp*nfe". The value
12 of unknown is not known , only that it will be in that position in each json response.

{
"A": {
"B": {
8 "unknown": {
"1": "F",
"maindata": [
{
"Info": "TEXT"
}
]
}
}
}
}

one line json

'{"A":{"B":{"unknown":{"1":"F","maindata":[{"Info":"TEXT"}]}}}}'

How would you get the value of "Text"? (I know how to load the json with json.loads)..but I'm not
sure how to get the value of "Text". Thanks.

(I'm not sure what the best title is.)

python dictionary python-2.7 nested

edited Jan 9 '13 at 3:10 asked Jan 9 '13 at 2:49


user1959942
123 1 1 5

3 Answers Active Oldest Votes

1 of 4 8/6/2020, 8:37 PM
Find a value within nested json dictionary in python - Stack Overflow https://stackoverflow.com/questions/14227561/find-a-value-within-nested...

It is a bit lenghty, but in that example above:

18 In [1]: import json

In [2]: s = """\
...: {
...: "A": {
...: "B": {
...: "unknown": {
...: "1": "F",
...: "maindata": [
...: {
...: "Info": "TEXT"
...: }
...: ]
...: }
...: }
...: }
...: }"""

In [3]: data = json.loads(s)

In [4]: data['A']['B']['unknown']['maindata'][0]['Info']
Out[4]: u'TEXT'

You basically treat it as a dictionary, passing the keys to get the values of each nested
dictionary. The only different part is when you hit maindata , where the resulting value is a list.
In order to handle that, we pull the first element [0] and then access the Info key to get the
value TEXT .

In the case of unknown changing, you would replace it with a variable that represents the
'known' name it will take at that point in your code:

my_variable = 'some_name'
data['A']['B'][my_variable]['maindata'][0]['Info']

And if I would have actually read your question properly the first time, if you don't know what
unknown is at any point, you can do something like this:

data['A']['B'].values()[0]['maindata'][0]['Info']

Where values() is a variable containing:

[{u'1': u'F', u'maindata': [{u'Info': u'TEXT'}]}]

A single-item list that can be accessed with [0] and then you can proceed as above. Note
that this is dependent on there only being one item present in that dictionary - you would need
to adjust a bit if there were more.

edited Jan 9 '13 at 3:03 answered Jan 9 '13 at 2:57


RocketDonkey
31.2k 7 71 82

2 of 4 8/6/2020, 8:37 PM
Find a value within nested json dictionary in python - Stack Overflow https://stackoverflow.com/questions/14227561/find-a-value-within-nested...

I don't know what the value of unknown will be...so that won't work. Unknown could be any string.
– user1959942 Jan 9 '13 at 2:58

So you just need to access whatever is at that point, regardless of the name yeah? – RocketDonkey
Jan 9 '13 at 2:59

Yeah that's why its called unknown=P, otherwise it'd be easy to get. – user1959942 Jan 9 '13 at
2:59

You can use a recursive function to dig through every layer and print its value with an indent

2 def recurse_keys(df, indent = ' '):


'''
import json, requests, pandas
r = requests.post(...)
rj = r.json() # json decode results query
j = json.dumps(rj, sort_keys=True,indent=2)
df1 = pandas.read_json(j)
'''
for key in df.keys():
print(indent+str(key))
if isinstance(df[key], dict):
recurse_keys(df[key], indent+' ')
recurse_keys(df1)

answered Nov 6 '14 at 14:34


nagordon
959 1 9 14

As you said that unknown was at a fixed place You can do the following

2 import json
s=json.loads('{"A":{"B":{"unknown":{"1":"F","maindata":[{"Info":"TEXT"}]}}}}')
i=s["A"]["B"].keys()
x=i[0] # Will store 'unknown' in x, whatever unknown is
print s['A']['B'][x]['maindata'][0]['Info'] #here x dictionary index is used after B
as its value will be the value for unknown

This should do the job, since only the unknown key is really 'unknown'

answered Jan 9 '13 at 3:26


minocha
1,003 1 11 26

i realized now that RocketDonkey has mentioned this later in his post ! :) – minocha Jan 9 '13 at 3:37

@RocketDonkey - indeed thats what a new user needs ! :D – minocha Jan 10 '13 at 5:08

3 of 4 8/6/2020, 8:37 PM
Find a value within nested json dictionary in python - Stack Overflow https://stackoverflow.com/questions/14227561/find-a-value-within-nested...

4 of 4 8/6/2020, 8:37 PM

You might also like