Menu Close

Python JSON Module

Hello Programmer, In this article, we are going to learn about the Python JSON module along with various examples. Python JSON module provides a facility to work with JSON data.

Here we will see how to convert Python dictionary to JSON and vice-versa step by step.

At the end of this Python JSON module tutorial, you are completely able to work with the Python JSON module. In previous tutorials, we have seen lots of Python built-in modules along with examples.

Python JSON Module

JSON stands for JavaScript Object Notation. JSON is a data format that is used for representing structured data. JSON is commonly used to send and receive data between server and client.

You should have remember some important points of JSON.

  • JSON stands for JavaScript Object Notation.
  • JSON is used for transmitting data between server and client.
  • JSON is text, written in JavaScript Object Notation.
  • JSON is the syntax for storing and exchanging data.
  • JSON is the most popular data format used for representing data structure.

To use the Python JSON module you need to import the Python JSON module using the import keyword.

Python JSON loads()

To convert JSON into Python object, use json.loads() method.

Example:


import json

#json 
x = '{"name": "Programming", "tutorial": "Python", "url": "programmingfunda.com"}'

#parse x
y = json.loads(x)
print(y)

#get particular item from Dictionary
print(y['tutorial'])

Output

{'name': 'Programming', 'tutorial': 'Python', 'url': 'programmingfunda.com'}
Python

Python JSON dumps()

To convert Python Dictionary object to JSON, use json.dumps() method.

Example:


import json

#Python Dictionary
x = {'name': 'Programming', 'tutorial': 'Python', 'url': 'programmingfunda.com'}

#convert into JSON
y = json.dumps(x)
print(y)

#Check type 
print(type(y))

Output

{"name": "Programming", "tutorial": "Python", "url": "programmingfunda.com"}
<class 'str'>

You can convert Python objects of the following types, into JSON strings:-

dict
list
tuple
string
int
float
True
False
None

Example:


import json
print(json.dumps({"first_name": "Vishvajit", "last_name": "Rao"}))
print(json.dumps([1, 2, 3, 4, 5]))
print(json.dumps((1, 2, 3, 4, 5)))
print(json.dumps("Programming Funda"))
print(json.dumps(123))
print(json.dumps(12.90))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))

Output

{"first_name": "Vishvajit", "last_name": "Rao"}
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
"Programming Funda"
123
12.9
true
false
null

When you are converted Python object to JSON, Python object converted into JSON are equivalent:-

PythonJSON
dictObject
listArray
strString
intNumber
floatNumber
Nonenull
Falsefalse
Truetrue

Python pretty print JSON

Convert a Python object containing all the legal data types.

Example:


import json
x = {

"name": "Programming Funda",
"age":10,
"type":"Online learning platform",
"course": "Programming Language",

"languages":[
{"database":"Mysql","markup":"HTML and CSS"},
{"Server":"PHP","Programming":"Python"}

]
}

#Check type before conversion
print(type(x))

y = json.dumps(x)
print(y)

#Check type after conversion
print(type(y))

Output

<class 'dict'>
{"name": "Programming Funda", "age": 10, "type": "Online learning platform", "course": "Programming Language", "languages": [{"database": "Mysql", "markup": "HTML and CSS"}, {"Server": "PHP", "Programming": "Python"}]}
<class 'str'>

If you run the above code then you will get a JSON string, but it is not very easy to read, with no indentation and line breaks.

The json.dumps() has parameters to make JSON string easy to read.

Example:

Use the indent parameter to define the number of indents.

import json

x = {
"name": "Programming Funda",
"age":10,
"type":"Online learning platform",
"course": "Programming Language",

"languages":[
{"database":"Mysql","markup":"HTML and CSS"},
{"Server":"PHP","Programming":"Python"}

]
}
y = json.dumps(x, indent = 4)
print(y)

Output

{
    "name": "Programming Funda",
    "age": 10,
    "type": "Online learning platform",
    "course": "Programming Language",
    "languages": [
        {
            "database": "Mysql",
            "markup": "HTML and CSS"
        },
        {
            "Server": "PHP",
            "Programming": "Python"
        }
    ]
}

You can also define the separators, the default value is (“, “, “: “), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values.

Example:


import json

x = {

"name": "Programming Funda",
"age":10,
"type":"Online learning platform",
"course": "Programming Language",

"languages":[
{"database":"Mysql","markup":"HTML and CSS"},
{"Server":"PHP","Programming":"Python"}

]
}
y = json.dumps(x, indent = 4, separators=(". ", " = "))
print(y)

Output

{
    "name" = "Programming Funda".
    "age" = 10.
    "type" = "Online learning platform".
    "course" = "Programming Language".
    "languages" = [
        {
            "database" = "Mysql".
            "markup" = "HTML and CSS"
        }.
        {
            "Server" = "PHP".
            "Programming" = "Python"
        }
    ]
}

Order the result

The json.dumps() method has parameters to order the keys in the result:

Example

Use the sort_keys parameter to specify if the result should be sorted or not.


import json
x = {

"name": "Programming Funda",
"age":10,
"type":"Online learning platform",
"course": "Programming Language",

"languages":[
{"database":"Mysql","markup":"HTML and CSS"},
{"Server":"PHP","Programming":"Python"}

]
}
y = json.dumps(x, indent = 4, sort_keys = True)
print(y)

Output

{
    "age": 10,
    "course": "Programming Language",
    "languages": [
        {
            "database": "Mysql",
            "markup": "HTML and CSS"
        },
        {
            "Programming": "Python",
            "Server": "PHP"
        }
    ],
    "name": "Programming Funda",
    "type": "Online learning platform"
}

Conclusion

In this article, you have learned all about the Python JSON module using appropriate examples.
if you want to convert the Python Dictionary object to a JSON string, Then the Python JSON module in Python will be best for you.

If you like this article, please share and keep visiting for further Python internals modules tutorials.

Python built-in modules


For more information about the Python JSON module:- Click Here

Python Array Module Tutorial
Python Base64 Module Tutorial

Related Posts