w3resource

Pandas Series: to_json() function

Series-to_json() function

The to_json() function is used to convert an given 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:

Series.to_json(self, path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit='ms', default_handler=None, lines=False, compression='infer', index=True)
Pandas Series: str.to_json() function

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.
  • Series
    • default is 'index'
    • allowed values are: {'split','records','index','table'}
  • DataFrame
    • default is 'columns'
    • allowed values are: {'split','records','index','columns','values','table'}
  • The format of the JSON string
    • ‘split’ : dict like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
    • ‘records’ : list like [{column -> value}, … , {column -> value}]
    • ‘index’ : dict like {index -> {column -> value}}
    • ‘columns’ : dict like {column -> {index -> value}}
    • ‘values’ : just the values array
    • ‘table’ : dict like {‘schema’: {schema}, ‘data’: {data}} describing the data, and the data component is like orient='records'.
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 10 Required
force_ascii Force encoded string to be ASCII. bool, default 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 '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 None Required/td>
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 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 True Required

 

Returns: None or str
If path_or_buf is None, returns the resulting json format as a string. Otherwise returns None.

Example:

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame([['p', 'q'], ['r', 's']],
                   index=['row 1', 'row 2'],
                   columns=['col 1', 'col 2'])
df.to_json(orient='split')

Output:

'{"columns":["col 1","col 2"],"index":["row 1","row 2"],"data":[["p","q"],["r","s"]]}'

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

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame([['p', 'q'], ['r', 's']],
                   index=['row 1', 'row 2'],
                   columns=['col 1', 'col 2'])
df.to_json(orient='records')

Output:

'[{"col 1":"p","col 2":"q"},{"col 1":"r","col 2":"s"}]'

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

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame([['p', 'q'], ['r', 's']],
                   index=['row 1', 'row 2'],
                   columns=['col 1', 'col 2'])
df.to_json(orient='index')

Output:

'{"row 1":{"col 1":"p","col 2":"q"},"row 2":{"col 1":"r","col 2":"s"}}'

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

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame([['p', 'q'], ['r', 's']],
                   index=['row 1', 'row 2'],
                   columns=['col 1', 'col 2'])
df.to_json(orient='columns')

Output:

'{"col 1":{"row 1":"p","row 2":"r"},"col 2":{"row 1":"q","row 2":"s"}}'

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

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame([['p', 'q'], ['r', 's']],
                   index=['row 1', 'row 2'],
                   columns=['col 1', 'col 2'])
df.to_json(orient='values')

Output:

'[["p","q"],["r","s"]]'
Pandas Series: str.to_json() function

Example - Encoding with Table Schema:

Python-Pandas Code:

import numpy as np
import pandas as pd
df = pd.DataFrame([['p', 'q'], ['r', 's']],
                   index=['row 1', 'row 2'],
                   columns=['col 1', 'col 2'])
df.to_json(orient='table')

Output:

'{"schema": {"fields":[{"name":"index","type":"string"},{"name":"col 1","type":"string"},{"name":"col 2","type":"string"}],"primaryKey":["index"],"pandas_version":"0.20.0"}, "data": [{"index":"row 1","col 1":"p","col 2":"q"},{"index":"row 2","col 1":"r","col 2":"s"}]}'

Previous: Series-to_sql() function
Next: Series-to_clipboard() function



Follow us on Facebook and Twitter for latest update.