Pages

Monday 27 March 2023

Encoding/Decoding using Python JSON

Introduction

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is widely used in web applications to transfer data between client and server.


In Python, you can work with JSON data using the built-in json module. The json module provides methods for encoding Python data to JSON format and decoding JSON data to Python objects.


In this article, we will explore how to use the json module in Python with detailed examples.


Encoding Python Data to JSON

To encode Python data to JSON format, you can use the json.dumps() method. This method takes a Python object and returns a JSON string.


Encoding a Python Dictionary to JSON

Let's look at an example of encoding a Python dictionary to JSON format:

import json

# Define a Python dictionary
data = { "name": "John","age": 30,"city": "New York"}

# Encode the dictionary to JSON format
json_string = json.dumps(data)

# Print the JSON string
print(json_string)

By default, json.dumps() converts Python dictionaries to JSON objects, Python lists and tuples to JSON arrays, and Python strings to JSON strings.

Encoding a Python List to JSON

Let's look at an example of encoding a Python list to JSON format:

import json

# Define a Python list
data = ["John", 30, "New York"]

# Encode the list to JSON format
json_string = json.dumps(data)

# Print the JSON string
print(json_string)

Encoding a Python Tuple to JSON

Let's look at an example of encoding a Python tuple to JSON format:

import json

# Define a Python tuple

data = ("John", 30, "New York")

# Encode the tuple to JSON format

json_string = json.dumps(data)

# Print the JSON string
print(json_string)

Note that the encoded Python tuple is converted to a JSON array.

Encoding a Python Object to JSON

By default, the json.dumps() method cannot encode Python objects that are not a dictionary, list, tuple, string, number, or True, False, None.

However, you can provide a custom encoding function to handle such objects. The custom encoding function should take the object as input and return a JSON-serializable object.

Let's look at an example of encoding a Python object to JSON using a custom encoding function:

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

def encode_person(obj):
    if isinstance(obj, Person):
        return {"name": obj.name, "age": obj.age,"city": obj.city}
    else:
        raise TypeError("Object of type 'Person' is not JSON serializable")

# Define a Python object
person = Person("John", 30, "New York")
# Encode the object to JSON format using the custom encoding function

json_string = json.dumps(person, default=encode_person)

# Print the JSON string
print(json_string))


Decoding JSON to Python Objects

To decode JSON data to Python objects, you can use the json.loads() method. This method takes a JSON string and returns a Python object.

Decoding a JSON String to a Python Dictionary

Let's look at an example of decoding a JSON string to a Python dictionary:

import json

# Define a JSON string

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

# Decode the JSON string to a Python dictionary

data = json.loads(json_string)

# Print the Python dictionary
print(data)

Decoding a JSON String to a Python List

Let's look at an example of decoding a JSON string to a Python list:

import json

# Define a JSON string

json_string = '["John", 30, "New York"]'

# Decode the JSON string to a Python list

data = json.loads(json_string)

# Print the Python list
print(data))

Decoding a JSON String to a Python Tuple

Let's look at an example of decoding a JSON string to a Python tuple:

import json

# Define a JSON string

json_string = '["John", 30, "New York"]'

# Decode the JSON string to a Python tuple
data = tuple(json.loads(json_string))

# Print the Python tuple
print(data)

Decoding a JSON String to a Python Object

To decode a JSON string to a custom Python object, you can provide a custom decoding function to the json.loads() method. The custom decoding function should take a dictionary as input and return an object of the desired type.

Let's look at an example of decoding a JSON string to a custom Python object using a custom decoding function:

import json

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

def decode_person(dct):
    if "name" in dct and "age" in dct and "city" in dct:
        return Person(dct["name"], dct["age"], dct["city"])
    else:
        return dct

# Define a JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"}'

# Decode the JSON string to a custom Python object using the custom decoding function
person = json.loads(json_string, object_hook=decode_person)

# Print the custom Python object
print(person.name)
print(person.age)
print(person.city))

Writing JSON Data to a File

You can write JSON data to a file using the json.dump() method. This method takes a Python object and a file object, and writes the JSON data to the file.

Let's look at an example of writing a Python dictionary to a JSON file:

import json

# Define a Python dictionary
data = {"name": "John","age": 30,"city": "New York"}

# Write the dictionary to a JSON file
with open("data.json", "w") as f:
    json.dump(data, f)

Reading JSON Data from a File

You can read JSON data from a file using the json.load() method. This method takes a file object and returns a Python object.

Let's look at an example of reading a Python dictionary from a JSON file:

import json

# Read the JSON file and parse its contents into a Python dictionary
with open("data.json", "r") as f:
    data = json.load(f)

# Print the Python dictionary
print(data)

Handling JSON Exceptions

When working with JSON data, you may encounter exceptions if the JSON data is malformed or if the JSON data does not match the expected structure. It is important to handle these exceptions to prevent your program from crashing.

Handling JSONDecodeError

The json.loads() and json.load() methods raise a json.decoder.JSONDecodeError exception if the JSON data is malformed. You can catch this exception and handle it appropriately.

Let's look at an example of handling a JSONDecodeError exception:

import json
# Define a malformed JSON string for valid
#json_string = '{"name": "John", "age": 30, "city": "New York"}'

# Define a malformed JSON string for error handling
json_string = '{"name": "John", "age": 30, "city": "New York'


try:
# Try to decode the malformed JSON string

    data = json.loads(json_string)
except json.decoder.JSONDecodeError as e:
    # Handle the JSONDecodeError exception
    print(f"Malformed JSON: {e}")
else:
    # Print the Python dictionary
    print(data)

Handling KeyError

If the JSON data does not match the expected structure, you may encounter a KeyError when trying to access a non-existent key in a Python dictionary. You can catch this exception and handle it appropriately.

Let's look at an example of handling a KeyError exception:

import json
# Define a JSON string with missing keys
json_string = '{"name": "John", "city": "New York"}'

# Decode the JSON string to a Python dictionary
data = json.loads(json_string)

try:
    # Try to access a non-existent key in the Python dictionary
    age = data["age"]

except KeyError:
    # Handle the KeyError exception
    print("Missing key: age")
else:
    # Print the age
    print(age)

Conclusion

JSON is a lightweight and popular data interchange format that is widely used in web development and data exchange between applications. In Python, you can easily work with JSON data using the json module, which provides methods for encoding and decoding JSON data to and from Python objects. By mastering JSON in Python, you can easily integrate with other systems and services that use JSON as their data format.

Please subscribe my youtube channel for latest python tutorials and this article

2 comments: