save_json

pyhelpers.store.save_json(data, path_to_file, engine=None, verbose=False, **kwargs)[source]

Save data to a JSON file.

Parameters:
  • data (Any) – Data that could be dumped by as a JSON file.

  • path_to_file (str | os.PathLike) – Path where a JSON file is saved.

  • engine (str | None) – An open-source module used for JSON serialization; valid options include None (default, for the built-in json module), 'ujson' (for UltraJSON), 'orjson' (for orjson) and 'rapidjson' (for python-rapidjson).

  • verbose (bool | int) – Whether to print relevant information in console; defaults to False.

  • kwargs – [Optional] parameters of json.dump() (if engine=None), orjson.dumps() (if engine='orjson'), ujson.dump() (if engine='ujson') or 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