- Python JSON – Complete Tutorial
- Table of contents
- What is JSON?
- JSON syntax
- Collection of name/value pairs
- An ordered list of values
- JSON constraints
- What does JSON data look like?
- Working with Python JSON module
- Serializing Python objects to JSON format
- Serializing Python data using dumps()
- Deserializing JSON data to Python object
- Deserializing string using loads()
- Reading JSON data in Python
- Reading data from a file using load()
- Reading data from files using loads()
- Writing JSON data into a file in Python
- Writing data into the file using dump()
- Writing data into files using dumps()
- Encoding and decoding custom JSON objects in Python
- Example of custom object encoding in Python
- Example of custom object decoding in Python
- How to pretty print JSON data in Python?
- Pretty printing JSON using dumps()
- Pretty printing JSON using json.tools module
- How to sort JSON keys in Python?
- Summary
- How to Convert Python Class Object to JSON?
- Syntax of json.dumps()
- Examples
- 1. Convert class object to JSON string
- 2. Convert properties of class object to JSON string
- Summary
- Python print object as JSON | Example code
- Python example print object as json
Python JSON – Complete Tutorial
JSON (JavaScript Object Notation) is a popular data format representing structured data. It is used extensively in APIs and web applications. You can use the built-in Python JSON module that provides all the necessary methods for working with JSON data. This article covers the standard Python JSON module and explains how to parse, serialize, deserialize, encode, decode, and pretty-print its data.
Table of contents
What is JSON?
JSON is a popular lightweight data-interchange format inspired by JavaScript object syntax format specified by RFC 7159 and ECMA-404. The primary purpose of JSON format is to store and transfer data between the browser and the server, but it is widely used by microservice APIs for data exchange.
JSON syntax
The syntax of JSON is straightforward. It is built on top of two simple structures:
- A collection of name/value pairs (in Python, they are represented as a Python dictionary).
- An ordered list of values.
Here are examples of these simple universal data structures.
Collection of name/value pairs
Name/value pairs form a JSON object which is described using curly braces < >. You can define a JSON object in the formatted form:
Or as a single string (both objects are the same):
An ordered list of values
An ordered list of items is defined using the square brackets [ ] and holds any values separated by a comma ( , ):
The same ordered list of items can be defined as a single string:
JSON constraints
JSON format has several constraints:
- The name in name/value pairs must be defined as a string in double quotes ( » ).
- The value must be of the valid JSON data type :
- String – several plain text characters
- Number – an integer
- Object – a collection of JSON key/value pairs
- Array – an ordered list of values
- Boolean – true or false
- Null – empty object
What does JSON data look like?
Here’s an example of JSON data structure:
, "good_writer": false, "finished_this_article": null >
Working with Python JSON module
JSON is a standard data exchange format used by many programming languages, including Python. JSON (JavaScript Object Notation) represents data in a human-readable text format and is easy for computers to process. Python provides a built-in module called JSON to work with JSON data. The JSON module allows you to convert Python objects into JSON strings and back up again. It also provides methods for loading and saving JSON files.
In addition, the json module can also be used to convert Python dictionaries into JSON objects, it contains methods for processing JSON data, including the following operations: parsing, serializing, deserializing, encoding, decoding, and pretty-printing. Overall, the json module makes it easy to work with JSON data in Python programming language.
Serializing Python objects to JSON format
Serialization is translating a data structure into a format that can be stored, transmitted, and reconstructed later. Applicable to Python, serialization means that we will translate Python basic data types to JSON format. The json module can convert Python dictionaries or lists objects into a JSON format (string).
Here’s how Python json module handles the serialization process:
Serializing Python data using dumps()
Here’s an example of serializing Python data structure to the JSON formatted Python string using the dumps() method:
/files" python_data = < "user": < "name": " kamil", "age": 43, "Place": "Ethiopia", "gender": "male" >> json_string = json.dumps(python_data) print(f'JSON string: ')
Here’s an execution output:
Deserializing JSON data to Python object
The deserialization process is the opposite of serialization. It converts JSON data into a Python list or dictionary object.
Here’s how Python json module handles the deserialization process:
Deserializing string using loads()
To deserialize JSON formatted string to a Python object, you need to use the loads() method.
/files" python_data = None # read JSON file with open(f"/json_data.json", "r") as file_stream: data = file_stream.read() print(f'data variable type: ') print(f'data variable content: ') python_data = json.loads(data) print(f'Deserialized data type: ') print(f'Deserialized data: ')
Here’s an execution output:
Reading JSON data in Python
Depending on the JSON data source type (JSON formatted string or JSON formatted stream), there’re two methods available in Python json module to handle the read operation:
- load() – reads a JSON formatted stream and creates a Python object out of it
- loads() – reads a JSON formatted string and creates a Python object out of it
Reading data from a file using load()
You need to use the load() method to read the JSON formatted stream and convert it into a Python object. JSON formatted stream is returned by the Python built-in open() method. For more information about file operations, we recommend the Working with Files in Python article.
#!/usr/bin/env python3 import json import pathlib BASE_DIR = pathlib.Path(__file__).parent.resolve() FILES_DIR = f"/files" python_data = None with open(f"/json_data.json", "r") as file_stream: python_data = json.load(file_stream) print(f'Python data: ')
Here’s an execution output:
Reading data from files using loads()
You need to use the loads() method to read the JSON formatted string and convert it into a Python object. JSON formatted string can be obtained from the file using the Python built-in open() method. We recommend the Working with Files in Python article for more information about file operations.
#!/usr/bin/env python3 import json import pathlib BASE_DIR = pathlib.Path(__file__).parent.resolve() FILES_DIR = f"/files" python_data = None with open(f"/json_data.json", "r") as file_stream: python_data = json.load(file_stream) print(f'Python data: ')
Here’s an execution output:
Writing JSON data into a file in Python
- dump() – converts Python object as a JSON formatted stream (usually used to save data straight to the file)
- dumps() – converts Python object as a JSON formatted string (produces a Python string object which can be written to the file)
Writing data into the file using dump()
To write the JSON formatted stream to a file, you need to use the json.dump() method in combination with the Python built-in open() method.
#!/usr/bin/env python3 import json import pathlib BASE_DIR = pathlib.Path(__file__).parent.resolve() FILES_DIR = f"/files" python_data = < "user": < "name": " kamil", "age": 43, "Place": "Ethiopia", "gender": "male" >> with open(f"/json_data.json", "w") as file_stream: json.dump(python_data, file_stream) file_stream.write('\n')
Writing data into files using dumps()
To write the JSON formatted string into a file, you need to use the json.dumps() method in combination with the Python built-in open() method.
#!/usr/bin/env python3 import json import pathlib BASE_DIR = pathlib.Path(__file__).parent.resolve() FILES_DIR = f"/files" python_data = < "user": < "name": " kamil", "age": 43, "Place": "Ethiopia", "gender": "male" >> with open(f"/json_data.json", "w") as file_stream: file_stream.write(json.dumps(python_data)) file_stream.write('\n')
Encoding and decoding custom JSON objects in Python
Although the json module can handle most built-in Python types. It doesn’t understand how to encode custom data types by default. If you need to encode a custom object, you can extend a JSONEncoder class and override its default() method. This method is used to JSONinfy custom objects.
Example of custom object encoding in Python
Let’s take a look at the example. Suppose you have a couple of user-defined classes: a Student and an Address And you want to serialize them to a JSON document.
Example of custom object decoding in Python
If you need to convert the JSON document into some other Python object (i.e., not the default dictionary), the simplest way of doing that is to use the SimpleNamespace class and the object_hook argument of the load() or the loads() method.
> """ student = json.loads(json_document, object_hook=lambda d: SimpleNamespace(**d)) print(f'='*25) print(f'Student information:') print(f'='*25) print(f' Name: ') print(f' Age: ') print(f' Address:') print(f' Street: ') print(f' City: ') print(f' Zip: ')
How to pretty print JSON data in Python?
- Use indent argument of the dumps() method – this is an ideal option when you’re printing JSON messages from your Python code
- Use the json.tool module – you can use this method when you need to format a JSON message in your shell
Pretty printing JSON using dumps()
Pretty printing JSON using the dumps() method is straightforward:
> """ data = json.loads(json_document) print('Pretty printed JSON:') print(json.dumps(data, indent=4))
The indent argument defines an indentation (number or spaces) for JSON objects during the print operation.
Here’s an execution output:
Pretty printing JSON using json.tools module
To format JSON documents in your shell without using third-party tools, you can use json.tool Python module:
How to sort JSON keys in Python?
When you need to sort JSON keys (sort JSON objects by name), you can set the sort_keys argument to True in the dumps() method:
#!/usr/bin/env python3 import json json_document = """ < "name": "Andrei", "age": 34, "address": < "city": "New York", "street": "475 48th Ave", "zipcode": "11109" >> """ data = json.loads(json_document) print('Pretty printed JSON:') print(json.dumps(data, indent=4, sort_keys=True))
Here’s an execution output:
Summary
This article covered the basics and advanced JSON processing technics in Python, including parsing, serializing, deserializing, encoding, decoding, and pretty-printing JSON data using Python. An ability to process JSON in Python is a must-have hands-on skill for every AWS automation engineer, for example, when you need to deal with DynamoDB stream processing in your AWS Lambda function.
How to Convert Python Class Object to JSON?
To convert a Python Class Object to JSON String, or save the parameters of the class object to a JSON String, use json.dumps() method.
In this tutorial, we will learn how to construct a JSON string from a Python class object.
Syntax of json.dumps()
Following is the syntax of json.dumps() function.
jsonStr = json.dumps(myobject.__dict__)
- json is the module.
- dumps is the method that converts the python object to JSON string. It returns a JSON string.
- myobject is the Python Class object and myobject.__dict__ gets the dictionary version of object parameters.
Examples
1. Convert class object to JSON string
In this example, we will define a Python class, create an object for the python class, and then convert its properties to a JSON string.
Python Program
import json class Laptop: name = 'My Laptop' processor = 'Intel Core' #create object laptop1 = Laptop() laptop1.name = 'Dell Alienware' laptop1.processor = 'Intel Core i7' #convert to JSON string jsonStr = json.dumps(laptop1.__dict__) #print json string print(jsonStr)
The property names are converted to JSON keys while the their values are converted to JSON values.
2. Convert properties of class object to JSON string
In the following example, we will define a Python class with different datatypes like string, int and float; create an object for the python class, and then convert the Python Class Object properties to a JSON string.
Python Program
import json class Laptop: def __init__(self, name, processor, hdd, ram, cost): self.name = name self.processor = processor self.hdd = hdd self.ram = ram self.cost = cost #create object laptop1 = Laptop('Dell Alienware', 'Intel Core i7', 512, 8, 2500.00) #convert to JSON string jsonStr = json.dumps(laptop1.__dict__) #print json string print(jsonStr)
Summary
In this Python JSON Tutorial, we learned to convert a Python Class Object to JSON String with the help of Python Examples.
Python print object as JSON | Example code
Use JSON package and print method to print objects as JSON in Python. json.dumps() converts Python objects into a json string. Every object has an attribute that is denoted by dict and this stores the object’s attributes in Python.
Python example print object as json
Simple example code converts Python objects to JSON data.
import json # Dict object: obj = < "name": "John", "class": "First", "age": 5 >print(type(obj)) # convert into JSON: json_data = json.dumps(obj) print(json_data)
Another example
class Student object to JSON.
import json # custom class class Student: def __init__(self, roll_no, name, age): self.roll_no = roll_no self.name = name self.age = age if __name__ == "__main__": # create two new student objects s1 = Student("101", "Tim", 16) s2 = Student("102", "Ken", 15) # convert to JSON format jsonstr1 = json.dumps(s1.__dict__) jsonstr2 = json.dumps(s2.__dict__) # print created JSON objects print(jsonstr1) print(jsonstr2)
Do comment if you have any doubts or suggestions on this Python JSON tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.