Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. json.dumps() / json.loads()

json.dumps() / json.loads()

Functions for converting between Python objects and JSON-formatted strings. Commonly used for exchanging data with APIs and reading or writing configuration files.

Syntax

import json

# Convert a Python object to a JSON string.
json_str = json.dumps(object, ensure_ascii=False, indent=2)

# Convert a JSON string to a Python object.
obj = json.loads(json_str)

# Write a Python object to a JSON file.
with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(object, f, ensure_ascii=False, indent=2)

# Read a JSON file and convert it to a Python object.
with open('data.json', 'r', encoding='utf-8') as f:
    obj = json.load(f)

Functions and Arguments

Function / ArgumentDescription
json.dumps(obj)Converts a Python object to a JSON string and returns it. Supports dict, list, str, int, float, bool, and None.
json.loads(s)Converts a JSON string to a Python object and returns it. JSON objects become dicts, and JSON arrays become lists.
json.dump(obj, fp)Writes a Python object as JSON to a file object.
json.load(fp)Reads JSON from a file object and converts it to a Python object.
ensure_ascii=FalseOutputs non-ASCII characters (such as Unicode text) as-is without escaping them. The default is True (escaped).
indent=2Formats the output with the specified number of spaces for indentation. Useful for debugging and improving readability.
sort_keys=TrueOutputs dictionary keys sorted in alphabetical order.

Sample Code

import json

# Use dumps() to convert a Python dict to a JSON string.
user = {'name': 'Alice', 'age': 30, 'active': True, 'score': None}
json_str = json.dumps(user, ensure_ascii=False)
print(json_str)
# Outputs: '{"name": "Alice", "age": 30, "active": true, "score": null}'

# Omitting ensure_ascii=False escapes non-ASCII characters.
print(json.dumps({'name': 'Tanaka Taro'}))
# Outputs: '{"name": "Tanaka Taro"}'

# Use indent to pretty-print the output.
pretty = json.dumps(user, ensure_ascii=False, indent=2)
print(pretty)
# Outputs the JSON formatted with indentation for readability.

# Use loads() to convert a JSON string to a Python object.
json_text = '{"title": "Python Basics", "pages": 300, "tags": ["beginner", "programming"]}'
data = json.loads(json_text)
print(data['title'])     # Outputs: 'Python Basics'
print(data['tags'][0])   # Outputs: 'beginner'

# Use dump() to write to a file.
config = {'host': 'localhost', 'port': 8080, 'debug': False}
with open('config.json', 'w', encoding='utf-8') as f:
    json.dump(config, f, ensure_ascii=False, indent=2)

# Use load() to read from a file.
with open('config.json', 'r', encoding='utf-8') as f:
    loaded = json.load(f)
print(loaded['port'])  # Outputs: 8080

# An invalid JSON string raises an error.
try:
    json.loads("{'key': 'value'}")  # Single quotes are not valid JSON.
except json.JSONDecodeError as e:
    print(f'JSON error: {e}')

Notes

json.dumps() converts to an in-memory string, while json.dump() writes directly to a file. Similarly, json.loads() converts from a string, and json.load() reads from a file. A helpful way to remember the difference is that the trailing s stands for "string".

The type mapping between Python and JSON is as follows: Python dict → JSON object, list/tuple → JSON array, str → JSON string, int/float → JSON number, True/Falsetrue/false, Nonenull.

When working with data that contains non-ASCII characters, always specify ensure_ascii=False. With the default setting (ensure_ascii=True), non-ASCII characters are escaped to \uXXXX sequences, which increases file size and reduces readability.

If you find any errors or copyright issues, please .