gws.lib.jsonx¶
JSON utilities.
Thin wrappers around the standard json module that read and write JSON strings and
files. Objects that are not JSON serializable are converted to their attribute dicts
(vars) or to strings, so that gws.Data objects can be serialized directly.
All errors are raised as Error.
Example:
s = gws.lib.jsonx.to_pretty_string({'a': 1, 'b': [1, 2]})
d = gws.lib.jsonx.from_string(s)
gws.lib.jsonx.to_path('/tmp/data.json', d)
Source code: gws.lib.jsonx
Package Contents¶
- gws.lib.jsonx.from_path(path: str)¶
Read a JSON file.
- Parameters:
path – Path to a UTF-8 encoded JSON file.
- Returns:
The decoded object.
- Raises:
Error – If the file cannot be read or is not valid JSON.
- gws.lib.jsonx.from_string(s: str)¶
Decode a JSON string.
- Parameters:
s – JSON string.
- Returns:
The decoded object, or an empty dict if the string is empty or blank.
- Raises:
Error – If the string is not valid JSON.
- gws.lib.jsonx.to_path(path: str, x, pretty: bool = False, ensure_ascii: bool = True, default=None)¶
Write an object to a JSON file, UTF-8 encoded.
- Parameters:
path – File path.
x – Object to write.
pretty – If
True, sort the keys and indent the output.ensure_ascii – If
True, escape non-ASCII characters.default – Function that returns a serializable version of an object that is not serializable otherwise. By default, objects are converted to their
vars, or to strings if they have none.
- Raises:
Error – If the object cannot be encoded or the file cannot be written.
- gws.lib.jsonx.to_pretty_string(x, ensure_ascii: bool = True, default=None) str¶
Encode an object as a JSON string with sorted keys and indentation.
- Parameters:
x – Object to encode.
ensure_ascii – If
True, escape non-ASCII characters.default – Function that returns a serializable version of an object that is not serializable otherwise. By default, objects are converted to their
vars, or to strings if they have none.
- Returns:
The JSON string.
- Raises:
Error – If the object cannot be encoded.
- gws.lib.jsonx.to_string(x, pretty: bool = False, ensure_ascii: bool = True, default=None) str¶
Encode an object as a JSON string.
- Parameters:
x – Object to encode.
pretty – If
True, sort the keys and indent the output.ensure_ascii – If
True, escape non-ASCII characters.default – Function that returns a serializable version of an object that is not serializable otherwise. By default, objects are converted to their
vars, or to strings if they have none.
- Returns:
The JSON string.
- Raises:
Error – If the object cannot be encoded.