---Advertisement---

Comprehensive Guide to Python JSON Operations: Encoding, Decoding, and File Handling

By Bhavani

Updated On:

---Advertisement---
ComprehensiveGuide to Python JSON

Python JSON: JSON (JavaScript Object Notation) is a widely used data format for data exchange between systems. In Python, JSON handling is efficient with the built-in json module. This guide explains Python JSON operations such as encoding, decoding, and reading JSON files with practical examples.


JSON is a text format inspired by JavaScript that is commonly used for data exchange. It represents data as key-value pairs, similar to Python dictionaries. JSON can be used in APIs, databases, and web services.

json

{

   “name”: “John”,

   “age”: 30,

   “married”: true

}


To work with JSON in Python, import the json module:

python

import json

  • dumps() – Encodes Python objects to JSON strings
  • dump() – Writes encoded JSON data to a file
  • loads() – Decodes JSON strings into Python objects
  • load() – Reads JSON data from a file and decodes it

Python objects can be converted into JSON format using the dumps() method.

python

import json

data = {

  “name”: “Alice”,

  “age”: 28,

  “hobbies”: [“reading”, “gaming”],

  “is_active”: True

}

json_data = json.dumps(data, indent=4, sort_keys=True)

print(json_data)

json

{

    “age”: 28,

    “hobbies”: [

        “reading”,

        “gaming”

    ],

    “is_active”: true,

    “name”: “Alice”

}


To save JSON data into a file, use the dump() method.

python

import json

data = {“name”: “Bob”, “age”: 35}

with open(‘data.json’, ‘w’) as file:

    json.dump(data, file, indent=4)

This creates a file named data.json with the given data.


To decode JSON data into Python objects, use loads() for JSON strings and load() for JSON files.

python

import json

json_string = ‘{“name”: “Ken”, “age”: 28, “is_married”: false}’

data = json.loads(json_string)

print(data)

python

{‘name’: ‘Ken’, ‘age’: 28, ‘is_married’: False}


To read JSON data directly from a file:

python

import json

with open(‘data.json’) as file:

    data = json.load(file)

print(data)


For space-efficient JSON output, use the separators parameter.

python

import json

data = [‘a’, ‘b’, ‘c’, {‘x’: 5, ‘y’: 10}]

compact_data = json.dumps(data, separators=(‘,’, ‘:’))

print(compact_data)

👉Output: [“a”,”b”,”c”,{“x”:5,”y”:10}]


For well-structured JSON output, use the indent parameter in dumps().

python

import json

data = {“a”: 4, “b”: 5}

formatted_json = json.dumps(data, indent=4)

print(formatted_json)

json

{

    “a”: 4,

    “b”: 5

}


To display JSON keys in alphabetical order:

python

import json

data = {

    “z”: 3,

    “a”: 1,

    “m”: 2

}

sorted_json = json.dumps(data, indent=4, sort_keys=True)

print(sorted_json)

json

{

    “a”: 1,

    “m”: 2,

    “z”: 3

}


For complex objects like complex numbers, you need a custom encoding function.

python

import json

def encode_complex(obj):

    if isinstance(obj, complex):

        return [obj.real, obj.imag]

    raise TypeError(“Object is not JSON serializable”)

complex_num = json.dumps(4 + 5j, default=encode_complex)

print(complex_num)

Output: [4.0, 5.0]


For decoding complex JSON data, use the object_hook parameter.

python

import json

def decode_complex(obj):

    if ‘__complex__’ in obj:

        return complex(obj[‘real’], obj[‘img’])

    return obj

json_data = ‘{“__complex__”: true, “real”: 4, “img”: 5}’

complex_object = json.loads(json_data, object_hook=decode_complex)

print(complex_object)

👉Output: (4+5j)


  • JSONEncoder encodes Python objects to JSON strings.
  • JSONDecoder decodes JSON strings into Python objects.

python

from json.encoder import JSONEncoder

data = {“colors”: [“red”, “green”, “blue”]}

encoded_data = JSONEncoder().encode(data)

print(encoded_data)

👉Output: ‘{“colors”: [“red”, “green”, “blue”]}’


python

from json.decoder import JSONDecoder

json_str = ‘{“name”: “Alice”, “age”: 30}’

decoded_data = JSONDecoder().decode(json_str)

print(decoded_data)

👉Output: {‘name’: ‘Alice’, ‘age’: 30}


While handling JSON data, common errors include:

  • JSONDecodeError – Incorrect JSON format
  • TypeError – Unsupported object type for encoding

python

import json

try:

    with open(‘invalid_file.json’) as file:

        data = json.load(file)

except json.JSONDecodeError:

    print(“Invalid JSON format!”)

How to Read CSV Files in Python

Download Python

Leave a Comment

Index