json-tricks: Extended JSON Serialization

3.17.3 · active · verified Thu Apr 16

json-tricks is a Python library that extends the standard `json` module with extra features like support for comments, preserving dictionary order, and native serialization/deserialization of complex types such as NumPy arrays, Pandas DataFrames/Series, datetime objects, and custom Python classes. It is currently at version 3.17.3 and is actively maintained with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to serialize and deserialize data containing NumPy arrays, datetime objects, and Pandas DataFrames using `json_tricks.dumps` and `json_tricks.loads`. It highlights the importance of `store_python_metadata=True` for successful round-tripping of complex types.

import json_tricks
import numpy as np
import datetime
import pandas as pd

# Example data with extended types
data = {
    'numbers': np.array([1, 2, 3]),
    'timestamp': datetime.datetime.now(),
    'dataframe': pd.DataFrame({'a': [1, 2], 'b': [3, 4]}),
    'mixed_list': [1, 'text', {'key': True}],
    'comments_example': '// This is a comment inside JSON' # Will be stripped unless allow_comments is used in dump
}

# Dump to a JSON string with metadata to enable full round-tripping
json_string = json_tricks.dumps(data, indent=4, store_python_metadata=True)
print('--- Dumped JSON ---')
print(json_string)

# Load from the JSON string
loaded_data = json_tricks.loads(json_string)

print('\n--- Loaded Data ---')
print(loaded_data)

# Verify types were restored
print(f"Type of 'numbers': {type(loaded_data['numbers'])} ")
print(f"Content of 'numbers': {loaded_data['numbers']}")
print(f"Type of 'timestamp': {type(loaded_data['timestamp'])}")
print(f"Type of 'dataframe': {type(loaded_data['dataframe'])}")

view raw JSON →