In this post, I’ll be exploring Python’s JSON module. I would suggest you go through json.org to get a better understanding of JSON if you’re not already aware of it.

Working with JSON is very simple in Python. Python already comes bundled with the json module which we would be seeing in this post.

The very first thing that we would do is, import the json module. Now, you can open the python interpreter or write it in a script or use some online coding platform to do it. I’ll leave the choice entirely up to you. So, let’s start.

import json

That should import the json module for you and we are good to go ahead now.

Converting from JSON to Python Object

The json module parses JSON either into a dictionary or a list in Python. To do that, it provides us with the load() and loads() methods. The difference between the two methods is that the former takes a file object as a parameter and the latter takes a JSON string as parameter.

import json
movies = '[{"title": "Despicable Me", "year": 2010, "watched": true}, {"title": "The Conjuring", "year": 2013, "watched": false}]'
json_to_python = json.loads(movies)

If you type print json_to_python, you should get the following output:

[{u'watched': True, u'title': u'Despicable Me', u'year': 2010}, {u'watched': False, u'title': u'The Conjuring', u'year': 2013}]

You can have the same JSON in a file and use the loads() method to convert it to a Python list like we did in the code above. Let’s see how we can do that.

import json
file_object = open("movies.json", "r")
json_to_python = json.load(file_object)

You should get the same output as you got above.

Converting from Python to JSON

In the earlier section, we covered how to convert JSON into a Python object. We’ll now see how we can do the other way round i.e. convert a Python object to JSON

import json
movies = [{'name': 'Finding Nemo', 'year': 2003, 'watched': True}, {'name': 'Fight Club', 'year': 1999, 'watched': False}]
python_to_json = json.dumps(movies)

If you print python_to_json, you will get the following JSON data:

[{"watched": true, "name": "Finding Nemo", "year": 2003}, {"watched": false, "name": "Fight Club", "year": 1999}]

And like we have load() for reading JSON data from a file, we have dump() for writing JSON data into a file and it’s fairly simple to write the code for it.

import json
file_object = open("movies.json", "w")
movies = [{'name': 'Finding Nemo', 'year': 2003, 'watched': True},
          {'name': 'Fight Club', 'year': 1999, 'watched': False}]
json.dump(movies, file_object)
file_object.close()

Once you run the code, you will see a file with the name movies.json which will contain the same output like the one above.

Working with your own types

We cannot simply store arbitrary Python objects as JSON. JSON can only deal with following objects:

  • numbers
  • character strings
  • None
  • booleans (True / False)
  • lists
  • dictionaries (only with character string keys)

Any object that is not one of the above must be converted.

import json

class Student(object):
    def __init__(self, roll_no, name, age):
        self.roll_no = roll_no
        self.name = name
        self.age = age

john = Student(1, 'John', 12)
json.dumps(john)

If you run the above code, it will fail and you’ll get a TypeError

To fix this, you have to define a default method for your class which should contain the following code:

def sdefault(obj):
    return obj.__dict__

Now you can encode the object into JSON with the following code:

json_data = json.dumps(john, default=sdefault)

Which will give the following output on printing json_data:

{"age": 12, "name": "John", "roll_no": 1}

You can name the default function anything you want.

Advertisements