-1

I have a JSON file with the following details:

{
"Name":"TESTING",
"Place":"India",
"Path":"Road",
"Details":
[
  {
    "city":"",
    "landmark":"aaabbbcccc",
    "pin":"500001"
  },
  {
    "city":"",
    "landmark":"aaabbbcccc",
    "pin":"500001"
  },
  {
    "city":"",
    "landmark":"xxxyyyzzzz",
    "pin":"510009"
  }
]
}

I want to parse the above json file and fetch the Name, Place, Path and store them into variables and then fetch city, landmark and pin and store them into arrays. How can i do this in Python. I've tried searching but all I could find is just reading the json file but not parsing it this way.

My Python code for reading the json:

import glob, os, json
from pprint import pprint
jsonfile = "testing.json"
with open('C:/Users/dev/Desktop/JSONSTest/'+jsonfile) as data_file:
    data = json.load(data_file)
pprint(data)
James Z
  • 12,209
  • 10
  • 24
  • 44
sdgd
  • 723
  • 1
  • 17
  • 38
  • 2
    You've done the parsing. Now `data` is a nested Python dictionary. There is nothing magical you need to do. – Daniel Roseman Nov 18 '17 at 20:04
  • How do i store them into my own variable names; like sname = "TESTING" – sdgd Nov 18 '17 at 20:06
  • 1
    Same way as any other dictionary lookup. If you don't know how to retrieve a key from a dictionary, you should do a [basic Python tutorial](https://sopython.com/wiki/What_tutorial_should_I_read%3F). – Daniel Roseman Nov 18 '17 at 20:07
  • 1
    Variable assignment like this sname = data['Name'] – Kishore Devaraj Nov 18 '17 at 20:08
  • Possible duplicate of [Parse JSON in Python](https://stackoverflow.com/questions/7771011/parse-json-in-python) – Elis Byberi Nov 18 '17 at 20:10
  • @KishoreDevaraj thanks. it helped. one last query. how can i get the city, landmark and pin from the file? using scity = data['city'] didn't fetch me any results. – sdgd Nov 18 '17 at 20:13
  • City, landmark, pin are in Detail list. you should try scity = data['Details'][0]['city']. Also like Daniel Roseman suggested take a look at that course. Learn about python dictionaries. – Kishore Devaraj Nov 18 '17 at 20:19
  • Thanks Kishore and Daniel. i tried the possibilities and it worked. I'll go through the documentations as well. – sdgd Nov 18 '17 at 20:20

1 Answers1

0

Try this to get cities:

for i in data['Details']:
    print i['city']
Andrii Pryimak
  • 797
  • 2
  • 10
  • 33