Python JSON

JSON is the most used data format when it comes to exchanging information between applications. When you want to use Python to communicate with APIs, it’s likely that you need to work with JSON.

Luckily, Python has a native module we can use to read, write, and parse JSON. In this lesson, we’ll look at how we can use JSON in Python.

First, you need to import the JSON module:

import json

Let’s see what we can do with this module.

Parse JSON to Dictionary

JSON in Python looks like JSON but in reality, it is probably a string. For example, look at this variable:

The variable “device_info” contains data formatted in JSON but it is a string. When you retrieve data through an API, it’s likely that you get your data like this.

To make it easy to work with this data, we’ll convert it into a python dictionary. We can use the json.loads() method to accomplish this. Here is an example:

We know how dictionaries work so this makes it easy to work with the data we received in JSON.

Parse Python Data Type to JSON

We can also parse Python objects to JSON with the json.dumps() method. This can be useful when you want to send data to an API. Python and JSON use different terminology:

Python JSON
Dictionary object
List or Tuple array
String string
Integer or Float number
True true
False false
None null

Let me show you an example where I convert the different Python objects into JSON:

As you can see above, a dictionary, list, string, and integer look the same but these objects are different:

  • True becomes true.
  • False becomes false.
  • None becomes null.

Formatting

The JSON module also supports formatting.

Indentation

Consider the following JSON string:

devices_string = '{"switches":[{"model":"CAT3750","model":"CAT2960"}],"routers":[{"model":"ISR1921","model":"CSR1000v"}]}'

This is valid JSON but it looks hard on the eyes. With the JSON module, we can format it with indentation so it’s easier to look at. This can be useful when you want to print JSON for a user of your program. Here is the code:

In the code above, we convert our JSON string into a dictionary, then back into JSON and we indent it with two spaces. The indented output is much easier to read.

Ordering

When we parse something into JSON, we can also sort the output by key. Here is an example:

As you can see above, the second output puts the “routers” key first.

Conclusion

You have now learned how to parse JSON in Python.

  • The JSON module lets you convert a JSON string into any of the Python data types or vice versa.
  • Using a Python dictionary is the most convenient way to work with JSON formatted data.

I hope you enjoyed this lesson. If you have any questions feel free to leave a comment!