save_json¶
- pyhelpers.store.save_json(data, path_to_file, engine=None, verbose=False, raise_error=False, **kwargs)[source]¶
Saves data to a JSON file.
- Parameters:
data (Any) –
Data to be serialised and saved as a JSON file.
path_to_file (str | os.PathLike) –
File path where the JSON file will be saved.
engine (str | None) –
Serialisation engine:
None
(default): Use the built-in json module.'ujson'
: Use UltraJSON for faster serialisation.'orjson'
: Use orjson for faster and more efficient serialisation.'rapidjson'
: Use python-rapidjson for fast and efficient serialisation.
verbose (bool | int) – Whether to print relevant information to the console; defaults to
False
.raise_error (bool) – Whether to raise the provided exception; if
raise_error=False
(default), the error will be suppressed.kwargs –
[Optional] Additional parameters for one of the following functions:
json.dump() (if
engine=None
)orjson.dumps() (if
engine='orjson'
)ujson.dump() (if
engine='ujson'
)rapidjson.dump() (if
engine='rapidjson'
)
Examples:
>>> from pyhelpers.store import save_json >>> from pyhelpers.dirs import cd >>> from pyhelpers._cache import example_dataframe >>> import json >>> json_pathname = cd("tests", "data", "dat.json") >>> json_dat = {'a': 1, 'b': 2, 'c': 3, 'd': ['a', 'b', 'c']} >>> save_json(json_dat, json_pathname, indent=4, verbose=True) Saving "dat.json" to ".\tests\data\" ... Done. >>> # Get an example dataframe >>> example_df = example_dataframe() >>> example_df Longitude Latitude City London -0.127647 51.507322 Birmingham -1.902691 52.479699 Manchester -2.245115 53.479489 Leeds -1.543794 53.797418 >>> # Convert the dataframe to JSON format >>> json_dat = json.loads(example_df.to_json(orient='index')) >>> json_dat {'London': {'Longitude': -0.1276474, 'Latitude': 51.5073219}, 'Birmingham': {'Longitude': -1.9026911, 'Latitude': 52.4796992}, 'Manchester': {'Longitude': -2.2451148, 'Latitude': 53.4794892}, 'Leeds': {'Longitude': -1.5437941, 'Latitude': 53.7974185}} >>> # Use built-in json module >>> save_json(json_dat, json_pathname, indent=4, verbose=True) Updating "dat.json" at ".\tests\data\" ... Done. >>> save_json(json_dat, json_pathname, engine='orjson', verbose=True) Updating "dat.json" at ".\tests\data\" ... Done. >>> save_json(json_dat, json_pathname, engine='ujson', indent=4, verbose=True) Updating "dat.json" at ".\tests\data\" ... Done. >>> save_json(json_dat, json_pathname, engine='rapidjson', indent=4, verbose=True) Updating "dat.json" at ".\tests\data\" ... Done.
See also
Examples for the function
load_json()
.