Masthead

Parsing JSON Data

Introduction

JSON is a very complicated language that is hierarchical as XML is. There is a Python library that makes it easy to parse JSON files. The "loads" function will parse a JSON file into a Python dictionary object, it's that easy!

Parsing JSON Data with the json library.

Note that the code below has the array we used in the last section but it is in quotes which makes it a string. Then, we use json.loads(TheJSON) to convert the string into a Python dictionary.

import json

TheJSON="""[
    {
        "Species": "Sequoia sempervirens",
        "Latitude": 40.509281,
        "Longitude": -123.893549
    },
    {
        "Species": "Sequoia sempervirens",
        "Latitude": 41.139693,
        "Longitude": -123.975794
    }
]"""

ArrayOfDictionaryentries = json.loads(TheJSON)

print("The entire array: "+format(ArrayOfDictionaryentries))

Index=0
while (Index<len(ArrayOfDictionaryentries)):
	
	TheDictionary=ArrayOfDictionaryentries[Index]
	
	TheSpecies=TheDictionary["Species"];
	TheLatitude=TheDictionary["Latitude"];
	TheLongitude=TheDictionary["Longitude"];
	
	print("The species: "+format(TheSpecies))
	print("The location: "+format(TheLatitude)+", "+format(TheLongitude))
	
	Index+=1

 

Additional Resources

Python Documentation: JSON

W3Schools: Python JSON

© Copyright 2018 HSU - All rights reserved.