save_json

pyhelpers.store.save_json(json_data, path_to_json, engine=None, verbose=False, **kwargs)

Save data to a JSON file.

Parameters
  • json_data (any json data) – data that could be dumped by as a JSON file

  • path_to_json (str or os.PathLike[str]) – path where a json file is saved

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

  • verbose (bool or 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