Pandas DataFrame to_json() Method

Pandas DataFrame to_json() method is “used to convert the object to a JSON string.” 

Syntax

DataFrame.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)

Parameters

path_or_buf:  File path or object. The result is returned as a string if the path is not specified. The parameter is optional.

orient: Indication of expected JSON string format. The parameter is required.

  • 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’: dictionary like {‘index’ -> [index], ‘columns’ -> [columns], ‘data’ -> [values]}
    • ‘records’: list like [{column -> value}, … , {column -> value}]
    • ‘index’: dictionary like {index -> {column -> value}}
    • ‘columns’: dictionary like {column -> {index -> value}}
    • ‘values’: just the values array.
    • ‘table’: dictionary like {‘schema’: {schema}, ‘data’: {data}} describing the data, and a data component is like orient=’records’.

date_format: The time unit to encode to govern timestamp and ISO8601 precision. One of ‘s’, ‘ms’, ‘us’, ‘ns’ for a second, millisecond, microsecond, and nanosecond, respectively. The parameter is optional.

default_handler: Handler to call if the object cannot be converted to a suitable format for JSON. Should receive a single argument, which is the object to convert and return a serializable object. This parameter is optional.

lines: If ‘orient’ is ‘records’, write outline delimited json format. Will throw ValueError if incorrect ‘orient’ since others are not like lists. The parameter is optional.

compression: A string representing a compression in the output file, only used when the first argument is the filename. By default, compression is inferred from the filename. This parameter is optional.

index: Whether to include index values in the JSON string. Not including an index (index=False) is only supported when the orient is ‘split’ or ‘table’. This parameter is optional.

Return Value

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

Example 1: How to Use Pandas DataFrame to_json() Method

import pandas as pd

# Creating Dataframe
df = pd.DataFrame(
    [['Stranger Things', 'Money Heist'], ['Most Dangerous Game', 'The Stranger']],
     columns=['Netflix', 'Quibi'])

print(df)

Output

    Netflix               Quibi
0  Stranger Things      Money Heist
1  Most Dangerous Game  The Stranger

Let’s convert DataFrame to JSON using the to_json() function.

import pandas as pd

# Creating Dataframe
df = pd.DataFrame(
    [['Stranger Things', 'Money Heist'], ['Most Dangerous Game', 'The Stranger']],
    columns=['Netflix', 'Quibi'])


data = df.to_json(orient='index')
print(data)

Output

{"0":{"Netflix":"Stranger Things","Quibi":"Money Heist"},
"1":{"Netflix":"Most Dangerous Game","Quibi":"The Stranger"}}

Example 2: orient = ‘columns’

import pandas as pd

# Creating Dataframe
df = pd.DataFrame(
     [['Stranger Things', 'Money Heist'], ['Most Dangerous Game', 'The Stranger']],
     columns=['Netflix', 'Quibi'])


data = df.to_json(orient='columns')
print(data)

Output

{"Netflix":{"0":"Stranger Things","1":"Most Dangerous Game"},
 "Quibi":{"0":"Money Heist","1":"The Stranger"}}

Example 3: orient=’table’

import pandas as pd

# Creating Dataframe
df = pd.DataFrame(
     [['Stranger Things', 'Money Heist'], ['Most Dangerous Game', 'The Stranger']],
      columns=['Netflix', 'Quibi'])


data = df.to_json(orient='table')
print(data)

Output

{"schema":{"fields":[{"name":"index","type":"integer"},
                     {"name":"Netflix","type":"string"},
                     {"name":"Quibi","type":"string"}],
                     "primaryKey":["index"],"pandas_version":"1.4.0"},
                     "data":[{"index":0,"Netflix":"Stranger Things",
                     "Quibi":"Money Heist"},{"index":1,
                     "Netflix":"Most Dangerous Game","Quibi":"The Stranger"}]}

Example 4: orient=’ values’

import pandas as pd

# Creating Dataframe
df = pd.DataFrame([['Stranger Things', 'Money Heist'],
                  ['Most Dangerous Game', 'The Stranger']],
                  columns=['Netflix', 'Quibi'])

# Convert DataFrame to JSON
data = df.to_json(orient='values')
print(data)

Output

[["Stranger Things","Money Heist"],["Most Dangerous Game","The Stranger"]]

Example 5: orient=’index’

# app.py

import pandas as pd

# Creating Dataframe
df = pd.DataFrame([['Stranger Things', 'Money Heist'],
     ['Most Dangerous Game', 'The Stranger']],
     columns=['Netflix', 'Quibi'])

# Convert DataFrame to JSON
data = df.to_json(orient='index')
print(data)

Output


{"0":{"Netflix":"Stranger Things","Quibi":"Money Heist"},
"1":{"Netflix":"Most Dangerous Game","Quibi":"The Stranger"}}

Example 6: orient=’records’

import pandas as pd

# Creating Dataframe
df = pd.DataFrame([['Stranger Things', 'Money Heist'],
 ['Most Dangerous Game', 'The Stranger']],
 columns=['Netflix', 'Quibi'])

# Convert DataFrame to JSON
data = df.to_json(orient='records')
print(data)

Output

[{"Netflix":"Stranger Things","Quibi":"Money Heist"},
{"Netflix":"Most Dangerous Game","Quibi":"The Stranger"}]

Example 7: orient=’split’

import pandas as pd

# Creating Dataframe
df = pd.DataFrame([['Stranger Things', 'Money Heist'],
 ['Most Dangerous Game', 'The Stranger']],
 columns=['Netflix', 'Quibi'])

# Convert DataFrame to JSON
data = df.to_json(orient='split')
print(data)

Output

{"columns":["Netflix","Quibi"],"index":[0,1],"data":[["Stranger Things","Money Heist"],
["Most Dangerous Game","The Stranger"]]}

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.