Use of Python json library

Using the Python json Library

JSON (JavaScript Object Notation) is a lightweight data exchange format that’s easy to read and write, and is commonly used for data exchange between front-end and back-end servers. Python provides the json library for converting Python objects into JSON-formatted strings, and vice versa.

JSON Format

First, let’s take a look at the JSON formatting rules.

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly brackets hold objects
  • Square brackets hold arrays

The following is an example of a simple JSON object:

{
"name": "John",
"age": 30,
"city": "New York"
}

Converting Python Objects to JSON Strings Using the json Library

The dumps() method in the json library is used to convert Python objects to JSON strings.

For example, to convert a dictionary object to a JSON string:

import json

dict_obj = {'name': 'John', 'age': 30, 'city': 'New York'}
json_str = json.dumps(dict_obj)

print(json_str)
# Output: {"name": "John", "age": 30, "city": "New York"}

In the above code, the dumps() method is used to convert a dictionary object to a JSON-formatted string. The dict_obj parameter specifies the Python object to be converted.

Converting JSON Strings to Python Objects Using the json Library

The loads() method in the json library is used to convert a JSON-formatted string to a Python object.

For example, to convert a JSON string into a Python object:

import json

json_str = '{"name": "John", "age": 30, "city": "New York"}'
dict_obj = json.loads(json_str)

print(dict_obj)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}

In the above code, the loads() method is used to convert a JSON string into a Python object. The json_str parameter specifies the JSON string to be converted.

Reading JSON File Contents

After saving JSON data in a file, you can use the json library to read and convert it into a Python object.

For example, to read data from the data.json file:

import json

with open('data.json', 'r') as f:
json_str = f.read()
dict_obj = json.loads(json_str)

print(dict_obj)
# Output: {'name': 'John', 'age': 30, 'city': 'New York'}

In the above code, the open() function is used to open the data.json file, and the read() method is used to read the JSON string. The loads() method in the json library is then used to convert the JSON string into a Python object.

Writing Python Objects to JSON Files

The json library can also be used to write Python objects to JSON files.

For example, to write a Python object to the file data.json:

import json

dict_obj = {'name': 'John', 'age': 30, 'city': 'New York'}

with open('data.json', 'w') as f:
json.dump(dict_obj, f)

In the above code, the json.dump() method is used to write the Python object dict_obj to the file data.json. The f parameter specifies the file object to store the data.

Custom JSON Encoder

The json library provides default encoding rules when converting Python objects to JSON strings. If you require specific encoding rules, you can customize the JSON encoder. Custom encoders are implemented by inheriting from json.JSONEncoder.

For example, to convert a custom class Person to a JSON string:

import json

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

class PersonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Person):
return {"name": obj.name, "age": obj.age}
return super().default(obj)

person_obj = Person("John", 30)

json_str = json.dumps(person_obj, cls=PersonEncoder)

print(json_str)
# Output: {"name": "John", "age": 30}

In the above code, a custom class, Person, is created. It inherits from json.JSONEncoder and implements a default() method. This method is called when converting a Python object to a JSON string. If the object is an instance of the Person class, it is converted to JSON format. Otherwise, the parent class’s default() method is called to convert the object to a JSON string in the default format.

When converting the person_obj object to a JSON string, the cls parameter specifies the custom encoder, PersonEncoder.

Custom JSON Decoder

When converting JSON strings to Python objects, the json library provides default decoding rules. If you require specific decoding rules, you can define a custom JSON decoder. Custom decoders are implemented by inheriting from json.JSONDecoder.

For example, a custom decoder converts a JSON string into a custom class Person:

import json

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

class PersonDecoder(json.JSONDecoder):
def decode(self, json_str):
dict_obj = json.loads(json_str)
return Person(dict_obj["name"], dict_obj["age"])

json_str = '{"name": "John", "age": 30}'
person_obj = json.loads(json_str, cls=PersonDecoder)

print(person_obj.name)
print(person_obj.age)
# Output:
# John
# 30

In the above code, a custom class, Person, is created. It inherits from json.JSONDecoder and implements a decode() method. This method is called when converting a JSON string to a Python object, converting a JSON-formatted dictionary into an instance of the Person class.

When converting the json_str string to a Python object, the cls parameter specifies the custom decoder, PersonDecoder, to use.

Summary

This article introduced the basic usage of the Python json library, including converting Python objects into JSON strings, converting JSON strings into Python objects, reading JSON file contents, and writing Python objects to JSON files. It also explained how to customize JSON encoders and decoders.

The json library is simple and easy to use, offering both convenience and flexibility, making it suitable for scenarios such as front-end and back-end data exchange and data storage.

Leave a Reply

Your email address will not be published. Required fields are marked *