Parsing json - dictionary with in dictionary - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Parsing json - dictionary with in dictionary (/thread-20088.html) |
Parsing json - dictionary with in dictionary - krish216 - Jul-26-2019 Hello I want to extract the value of all pr1 from location1 & 2 from below json - Any ideas would be appreciated import json jsonget = { "data":[ { "location1":[ { "pr1":"hn1", "pr2":"2019-08-07" } ] }, { "location2":[ { "pr1":"hn2", "pr2":"2019-08-07" } ] } ] } if __name__ == '__main__': jsonout = json.dumps(jsonget) jsonout1 = json.loads(jsonout) for val in jsonout1['data']: print val['location1']
RE: Parsing json - dictionary with in dictionary - ichabod801 - Jul-26-2019 The second item in 'data' has the key 'location2', but not the key 'location1'. RE: Parsing json - dictionary with in dictionary - krish216 - Jul-29-2019 Can you help with a snippet to extract pr1 for each location .. Here is how output should like location1 hn1 location2 hn2. Thank you. RE: Parsing json - dictionary with in dictionary - ichabod801 - Jul-29-2019 I would loop through the sub-dictionaries (for sub_dict in val.values()), and if the key you are looking for is in there, you can extract it. RE: Parsing json - dictionary with in dictionary - cvsae - Jul-29-2019 (Jul-29-2019, 08:53 PM)krish216 Wrote: Can you help with a snippet to extract pr1 for each location .. import json jsonget = { "data":[ { "location1":[ { "pr1":"hn1", "pr2":"2019-08-07" } ] }, { "location2":[ { "pr1":"hn2", "pr2":"2019-08-07" } ] } ] } if __name__ == '__main__': jsonout = json.dumps(jsonget) jsonout1 = json.loads(jsonout) for val in jsonout1['data']: key = val.keys()[0] print key, val[key][0]["pr1"] RE: Parsing json - dictionary with in dictionary - krish216 - Jul-30-2019 Thanks @cvsae for the quick help. RE: Parsing json - dictionary with in dictionary - cvsae - Jul-30-2019 (Jul-30-2019, 09:26 PM)krish216 Wrote: Thanks @cvsae for the quick help.you're welcome |