How to Parse JSON String in Python

Last Updated : 16 Sep, 2025

The full form of JSON is JavaScript Object Notation. It’s a lightweight text format used for storing and transferring data. Python supports JSON through its built-in json module. To use this feature, we import the json package in our Python script.

Unlike reading JSON from files, JSON strings come directly as text data (e.g., API responses). Python allows us to convert these JSON strings into native Python objects (like dictionaries or lists).

Example: Reading JSON String in Python

We will be using Python’s json module, which offers several methods to work with JSON data. In particular:

  • json.loads(): Converts a JSON string s into a Python object (dict or list).
  • json.dumps(obj, indent=4): Converts the Python object back to a JSON string with pretty-printing.
Python
import json

j_string = '{"name": "Alice", "languages": ["English", "Spanish"]}'

data = json.loads(j_string)

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

Output:

{
"name": "Alice",
"languages": [
"English",
"Spanish"
]
}

In this example, we are reading a JSON string directly (not a file) and the output retains the same structured format as the original JSON content.

Error Handling While Reading JSON Strings

We can handle common errors while reading JSON strings using try-except blocks, making our code more reliable, maintainable and production-ready.

JSONDecodeError

This error occurs when the JSON string is malformed or not properly formatted. Handling it ensures our program doesn’t crash due to invalid JSON input.

  • try-except: Captures the error and allows us to handle it gracefully.
Python
import json

j_string = '{"name": "Alice", "languages": ["English", "Spanish"]'

try:
    data = json.loads(j_string)
    print("JSON string =", data)

except json.JSONDecodeError:
    print("Error: Failed to decode JSON string.")

Output if JSON string is malformed:

Error: Failed to decode JSON string.

Comment