2 min read

Python JSON Handling

JSON (JavaScript Object Notation) is a lightweight data interchange format. Python provides a built-in module called json for encoding and decoding JSON data.

Importing the Module

import json

Parsing JSON (Decoding)

To parse a JSON string and convert it into a Python dictionary, use the json.loads() method.

import json

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

# Parse JSON
data = json.loads(json_string)

print(data["age"]) # Output: 30

Generating JSON (Encoding)

To convert a Python object (like a dictionary) into a JSON string, use the json.dumps() method.

import json

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

# Convert to JSON
json_string = json.dumps(data)

print(json_string)

Formatting JSON

You can format the JSON output to make it more readable using the indent parameter.

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

You can also sort the keys using sort_keys=True.

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

Working with Files

Writing to a JSON File

Use json.dump() to write Python objects directly to a file.

import json

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

with open('data.json', 'w') as f:
    json.dump(data, f, indent=4)

Reading from a JSON File

Use json.load() to read JSON data directly from a file.

import json

with open('data.json', 'r') as f:
    data = json.load(f)
    print(data)

programming/python/python