In this module, we will learn about JSON in Python and cover the following topics.
If you have a JSON string or JSON data, you can easily parse it by using json.loads() method found in json package. To make use of this method, you have to import the json package that Python offers. As discussed above, this method is called deserialization, as we are converting JSon encoded data into a Python object. The deserialization takes place as per the following table.
For example, the JSON data of object type will be converted into a Python dictionary.
In the above example, intellipaat is a JSON string and intellipaat_dict is a Python dictionary.
We can also convert Python data into Json format using dumps() method as shown in the example below:
while converting Python objects into JSON, the Python object gets converted into the equivalent JSON type as per the following table:
Even though we have learned how to convert the Python object into JSON data, but it can still be very hard to read the converted JSON data, with no indentation and no line breaks. To make it more readable, there are various parameters of json.dumps() method that we can use.
We can also include various separators, such as comma and colon.
In certain cases where we might want to sort the resultant JSON data after converting it from Python to JSON, we can simply use another parameter of json.dumps() method which is, sort_keys.
Using this parameter, you can define if you want the result to be sorted or not using values such as true and false.
json.dumps(b, indent = 3, sort_keys=True)
With this we come to an end of this module, the next module highlights Python RegEx. See you there!Previous Next
Download Interview Questions asked by top MNCs in 2019?