pandas 1.4.2

NotesParametersReturns
to_json(self, path_or_buf: 'FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None' = None, orient: 'str | None' = None, date_format: 'str | None' = None, double_precision: 'int' = 10, force_ascii: 'bool_t' = True, date_unit: 'str' = 'ms', default_handler: 'Callable[[Any], JSONSerializable] | None' = None, lines: 'bool_t' = False, compression: 'CompressionOptions' = 'infer', index: 'bool_t' = True, indent: 'int | None' = None, storage_options: 'StorageOptions' = None) -> 'str | None'

Note NaN's and None will be converted to null and datetime objects will be converted to UNIX timestamps.

Notes

The behavior of indent=0 varies from the stdlib, which does not indent the output but does insert newlines. Currently, indent=0 and the default indent=None are equivalent in pandas, though this may change in a future release.

orient='table' contains a 'pandas_version' field under 'schema'. This stores the version of pandas used in the latest revision of the schema.

Parameters

path_or_buf : str, path object, file-like object, or None, default None

String, path object (implementing os.PathLike[str]), or file-like object implementing a write() function. If None, the result is returned as a string.

orient : str

Indication of expected JSON string format.

  • Series:

    • default is 'index'

    • allowed values are: {'split', 'records', 'index', 'table'}.

  • DataFrame:

    • default is 'columns'

    • allowed values are: {'split', 'records', 'index', 'columns', 'values', 'table'}.

date_format : {None, 'epoch', 'iso'}

Type of date conversion. 'epoch' = epoch milliseconds, 'iso' = ISO8601. The default depends on the :None:None:`orient`. For orient='table' , the default is 'iso'. For all other orients, the default is 'epoch'.

double_precision : int, default 10

The number of decimal places to use when encoding floating point values.

force_ascii : bool, default True

Force encoded string to be ASCII.

date_unit : str, default 'ms' (milliseconds)

The time unit to encode to, governs timestamp and ISO8601 precision. One of 's', 'ms', 'us', 'ns' for second, millisecond, microsecond, and nanosecond respectively.

default_handler : callable, default None

Handler to call if object cannot otherwise be converted to a suitable format for JSON. Should receive a single argument which is the object to convert and return a serialisable object.

lines : bool, default False

If 'orient' is 'records' write out line-delimited json format. Will throw ValueError if incorrect 'orient' since others are not list-like.

compression : str or dict, default 'infer'

For on-the-fly compression of the output data. If 'infer' and 'path_or_buf' path-like, then detect compression from the following extensions: '.gz', '.bz2', '.zip', '.xz', or '.zst' (otherwise no compression). Set to None for no compression. Can also be a dict with key 'method' set to one of { 'zip' , 'gzip' , 'bz2' , 'zstd' } and other key-value pairs are forwarded to zipfile.ZipFile , gzip.GzipFile , bz2.BZ2File , or zstandard.ZstdDecompressor , respectively. As an example, the following could be passed for faster compression and to create a reproducible gzip archive: compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1} .

versionchanged
index : bool, default True

Whether to include the index values in the JSON string. Not including the index ( index=False ) is only supported when orient is 'split' or 'table'.

indent : int, optional

Length of whitespace used to indent each record.

versionadded
storage_options : dict, optional

Extra options that make sense for a particular storage connection, e.g. host, port, username, password, etc. For HTTP(S) URLs the key-value pairs are forwarded to urllib as header options. For other URLs (e.g. starting with "s3://", and "gcs://") the key-value pairs are forwarded to fsspec . Please see fsspec and urllib for more details.

versionadded

Returns

None or str

If path_or_buf is None, returns the resulting json format as a string. Otherwise returns None.

Convert the object to a JSON string.

See Also

read_json

Convert a JSON string to pandas object.

Examples

This example is valid syntax, but we were not able to check execution
>>> import json
... df = pd.DataFrame(
...  [["a", "b"], ["c", "d"]],
...  index=["row 1", "row 2"],
...  columns=["col 1", "col 2"],
... )
This example is valid syntax, but we were not able to check execution
>>> result = df.to_json(orient="split")
... parsed = json.loads(result)
... json.dumps(parsed, indent=4) # doctest: +SKIP { "columns": [ "col 1", "col 2" ], "index": [ "row 1", "row 2" ], "data": [ [ "a", "b" ], [ "c", "d" ] ] }

Encoding/decoding a Dataframe using 'records' formatted JSON. Note that index labels are not preserved with this encoding.

This example is valid syntax, but we were not able to check execution
>>> result = df.to_json(orient="records")
... parsed = json.loads(result)
... json.dumps(parsed, indent=4) # doctest: +SKIP [ { "col 1": "a", "col 2": "b" }, { "col 1": "c", "col 2": "d" } ]

Encoding/decoding a Dataframe using 'index' formatted JSON:

This example is valid syntax, but we were not able to check execution
>>> result = df.to_json(orient="index")
... parsed = json.loads(result)
... json.dumps(parsed, indent=4) # doctest: +SKIP { "row 1": { "col 1": "a", "col 2": "b" }, "row 2": { "col 1": "c", "col 2": "d" } }

Encoding/decoding a Dataframe using 'columns' formatted JSON:

This example is valid syntax, but we were not able to check execution
>>> result = df.to_json(orient="columns")
... parsed = json.loads(result)
... json.dumps(parsed, indent=4) # doctest: +SKIP { "col 1": { "row 1": "a", "row 2": "c" }, "col 2": { "row 1": "b", "row 2": "d" } }

Encoding/decoding a Dataframe using 'values' formatted JSON:

This example is valid syntax, but we were not able to check execution
>>> result = df.to_json(orient="values")
... parsed = json.loads(result)
... json.dumps(parsed, indent=4) # doctest: +SKIP [ [ "a", "b" ], [ "c", "d" ] ]

Encoding with Table Schema:

This example is valid syntax, but we were not able to check execution
>>> result = df.to_json(orient="table")
... parsed = json.loads(result)
... json.dumps(parsed, indent=4) # doctest: +SKIP { "schema": { "fields": [ { "name": "index", "type": "string" }, { "name": "col 1", "type": "string" }, { "name": "col 2", "type": "string" } ], "primaryKey": [ "index" ], "pandas_version": "1.4.0" }, "data": [ { "index": "row 1", "col 1": "a", "col 2": "b" }, { "index": "row 2", "col 1": "c", "col 2": "d" } ] }
See :

Local connectivity graph

Hover to see nodes names; edges to Self not shown, Caped at 50 nodes.

Using a canvas is more power efficient and can get hundred of nodes ; but does not allow hyperlinks; , arrows or text (beyond on hover)

SVG is more flexible but power hungry; and does not scale well to 50 + nodes.

All aboves nodes referred to, (or are referred from) current nodes; Edges from Self to other have been omitted (or all nodes would be connected to the central node "self" which is not useful). Nodes are colored by the library they belong to, and scaled with the number of references pointing them


File: /pandas/core/generic.py#2355
type: <class 'function'>
Commit: