DataFrame: to_json()
Last update on February 26 2020
Pandas DataFrame: to_json() function
The to_json() function is used to convert the object to a JSON string.
Note: NaN's and None will be converted to null and datetime objects will be converted to UNIX timestamps.
Syntax:
Parameters:
Name | Description | Type/Default Value | Required / Optional |
path_or_buf | File path or object. If not specified, the result is returned as a string. | string or file handle | Optional |
orient | Indication of expected JSON string format.
| string | Required |
date_format | Type of date conversion. ‘epoch’ = epoch milliseconds, ‘iso’ = ISO8601. The default depends on the orient. For orient='table', the default is ‘iso’. For all other orients, the default is ‘epoch’. | {None, ‘epoch’, ‘iso’} | Required |
double_precision | The number of decimal places to use when encoding floating point values. | int Default Value: 10 | Required |
force_ascii | Force encoded string to be ASCII. | bool Default Value: True | Required |
date_unit | The time unit to encode to, governs timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’, ‘ns’ for second, millisecond, microsecond, and nanosecond respectively. | string Default Value: ‘ms’ (milliseconds) | Required |
default_handler | 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. | callable Default Value: None | Required |
lines | If 'orient' is 'records' write out line delimited json format. Will throw ValueError if incorrect 'orient' since others are not list like. | bool Default Value: False | Required |
compression | A string representing the compression to use in the output file, only used when the first argument is a filename. By default, the compression is inferred from the filename. | {'infer', 'gzip', 'bz2', 'zip', 'xz', None} | Required |
index | 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’. | bool Default Value: True | Required |
Returns: None or str If path_or_buf is None, returns the resulting json format as a string. Otherwise returns None.
Example:
In [11]:
Out[11]:
Encoding/decoding a Dataframe using 'records' formatted JSON:In [12]:
Out[12]:
Encoding/decoding a Dataframe using 'index' formatted JSON:In [13]:
Out[13]:
Encoding/decoding a Dataframe using 'columns' formatted JSON:In [14]:
Out[14]:
Encoding/decoding a Dataframe using 'values' formatted JSON:In [15]:
Out[15]:
Encoding with Table Schema:In [16]:
Out[16]:
Download the above Notebook from here.
Reference : https://www.w3resource.com/pandas/dataframe/dataframe-to_json.php
Last updated