DEV Community

Cover image for parse json with python
tcs224
tcs224

Posted on

parse json with python

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.

Usually web apps transfer JSON data back and forth. If you create your own web apps, they likely transfer JSON data (or XML). If you want to play around with the json format, here's a tool

So how do you work with Python and JSON?

First, you should already know the basics of Python programming.

Python and JSON

Python has a module named json. This lets you convert json data from the web to python objects and vice versa.

Consider this example in the Python interpreter:

>>> import json
>>> # json data
... 
>>> x = '{ "name":"Alicia", "age":30, "city":"Toronto"}'
>>> # prase json data
... 
>>> obj = json.loads(x)
>>> print(obj["name"]
... )
Alicia
>>> print(obj["city"])
Toronto
>>> 

It loads the json module, defines raw json data. Then converts the json data to a python object.

>>> obj = json.loads(x)

And then you can use it as Python object

>>> print(obj["name"])
>>> print(obj["city"])

You can load JSON data from a url or from a file.

Parse JSON

You've seen this above in the Python REPL, but for clarity lets put it in a code file. In code, to load json data and convert it to a Python object, you can do this:

import json

# json data                                                                     
data = '{ "name":"Alicia", "age":30, "city":"Toronto"}'

# parse json data                                                               
obj = json.loads(data)

# python object                                                                 
print(obj["name"])
print(obj["city"])

Save it as example.py and run it, you'll see it has been converted to a Python object. You can also decode a Python object to JSON amongst other things.

Top comments (0)