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!


Forum Replies

  1. Hi rene.

    In a json like this…

    {
        "routers": 
          {
            "name": "CSR1000V",
            "vendor": "Cisco",
            "type": "virtual"
          },
          {
            "name": "1921",
            "vendor": "Cisco",
            "type": "hardware"
          }
       
    }
    

    How can I select the “routers” label?

    In this json I have not the “[]” after “routers” labels.

    For example I have to select…if is there routers do something…if there a firewalls do something other…

    Thanks you

  2. Hi Giovanni,

    You probably already have an answer but just in case…

    When you want to “select” a certain field in a JSON (or dictionary), it’s best to use an IDE like vscode and use the debugger to select what you need. For example:

    Rene

  3. Hi Rene and staff,
    you don’t talk about CSV with python, so may i ask a question about python with CSV format in this section ?
    Example 1: let’s python read a csv file

    https://cdn-forum.networklessons.com/uploads/default/original/2X/6/6e7ed8c20c38eef173c196c7808b3d0000d1bbc9.png

    Exemple1 is a string, then apply csv.reader(): you get an object “_csv.reader” but this is not a loop object

    Example 2: just open the csv file

    https://cdn-forum.networklessons.com/uploads/default/original/2X/3/3b7fca38dffcb4d037d37e89965ed2ef7e66347f.png

    f is a _io.TextIOWrapper object,

    ... Continue reading in our forum

  4. Bonjour @syncope988,

    Using open or with open is the same thing, except when you use “with”, it automatically closes.

    First Example

    • You use the read() function on “f” and assign the output to the “exemple1” variable. When you use the read() function, you get a string.
    • You then run the reader() function from the CSV module, feed it the “exemple1” variable and assign the output to the “exemple_f” variable.
    • You then iterate over each item in the “exemple_f” variable.

    When you check what “row” is, you’ll see it’s a list with only a single character. That’s why you

    ... Continue reading in our forum

  5. Hi Rene,
    yes it helps a lot
    Great thanks
    Regards

4 more replies! Ask a question or join the discussion by visiting our Community Forum