Python

JSON

JSON (JavaScript Object Notation) is a standard text format used to store and transfer data. It is heavily used in web development and APIs.

In Python, JSON data looks almost exactly like a Python dictionary. To work with JSON, Python provides a built-in module called json.

Basic Concepts

  • Parsing (Decoding): Converting a JSON string into a Python dictionary.
  • Serializing (Encoding): Converting a Python dictionary into a JSON string.

1. Import the JSON Module

You must import the json module before you can use it. It comes built-in with Python, so no installation is required.

import json

2. JSON String to Python Dictionary (json.loads())

If you have a JSON string (maybe received from an API), you can parse it into a Python dictionary using json.loads() (load string).

import json

# A JSON string (Notice the single quotes outside, double quotes inside)
json_string = '{"name": "Ram", "age": 25, "city": "Kathmandu"}'

# Parse the string into a dictionary
user_dict = json.loads(json_string)

print(user_dict["name"])
print(type(user_dict))

Output:

Ram
<class 'dict'>

3. Python Dictionary to JSON String (json.dumps())

If you have a Python dictionary and want to send it over a network or save it as a text string, use json.dumps() (dump string).

import json

student = {
    "name": "Sita",
    "grade": "A",
    "is_active": True,
    "projects": None
}

# Convert dictionary to JSON string
json_data = json.dumps(student)

print(json_data)

Output:

(Notice how Python's True becomes true and None becomes null)

{"name": "Sita", "grade": "A", "is_active": true, "projects": null}

4. Pretty Printing JSON (Formatting)

Reading one long line of JSON is difficult. You can format it nicely using the indent parameter.

import json

student = {"name": "Hari", "age": 22, "skills": ["Python", "SQL"]}

# Add an indent of 4 spaces
formatted_json = json.dumps(student, indent=4)

print(formatted_json)

Output:

{
    "name": "Hari",
    "age": 22,
    "skills": [
        "Python",
        "SQL"
    ]
}

5. Sorting JSON Keys

You can also ask Python to sort the keys alphabetically using sort_keys=True.

import json

data = {"c": 3, "a": 1, "b": 2}

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

Output:

{
  "a": 1,
  "b": 2,
  "c": 3
}

6. Writing JSON to a File (json.dump())

Notice there is no "s" in this function name. json.dump() writes a Python dictionary directly into a file.

import json

data = {
    "users": [
        {"id": 1, "name": "Ram"},
        {"id": 2, "name": "Sita"}
    ]
}

with open("data.json", "w") as file:
    json.dump(data, file, indent=4)

print("JSON file created successfully.")

Output:

JSON file created successfully.

(This creates a file named data.json containing the formatted JSON text).

7. Reading JSON from a File (json.load())

Again, no "s". json.load() reads a file containing JSON and automatically converts it into a Python dictionary.

import json

# Assuming 'data.json' was created in the previous step
with open("data.json", "r") as file:
    parsed_data = json.load(file)

# Accessing the first user's name
print(parsed_data["users"][0]["name"])

Output:

Ram

Python vs JSON Data Types

When you convert between Python and JSON, the data types map like this:

Python TypeJSON Equivalent
dictObject ({})
list, tupleArray ([])
strString ("")
int, floatNumber
Truetrue
Falsefalse
Nonenull

Easy Way to Remember

  • Has an "s" (loads, dumps): Works with Strings in memory.
  • No "s" (load, dump): Works directly with Files.
Interactive Sandbox
Python