0
0
PandasHow-ToBeginner · 3 min read

How to Write JSON in Pandas: Syntax and Examples

You can write JSON from a pandas DataFrame using the to_json() method. This method converts the DataFrame into a JSON string or directly writes it to a file by specifying a file path.
📐

Syntax

The basic syntax to write JSON from a pandas DataFrame is:

  • DataFrame.to_json(path_or_buf=None, orient='columns', lines=False)

Where:

  • path_or_buf: file path or buffer to write JSON to. If None, returns JSON string.
  • orient: format of JSON string. Common options are 'columns', 'records', 'index'.
  • lines: if True, writes JSON as newline-delimited records.
python
df.to_json(path_or_buf=None, orient='columns', lines=False)
💻

Example

This example shows how to create a DataFrame and write it to a JSON file with different orientations.

python
import pandas as pd

# Create a sample DataFrame
data = {'name': ['Alice', 'Bob'], 'age': [25, 30], 'city': ['NY', 'LA']}
df = pd.DataFrame(data)

# Write DataFrame to JSON file with default orientation (columns)
df.to_json('output_columns.json')

# Write DataFrame to JSON file with records orientation (list of dicts)
df.to_json('output_records.json', orient='records')

# Write DataFrame to JSON file with lines=True (newline delimited JSON)
df.to_json('output_lines.json', orient='records', lines=True)

# Read back one file to show output
with open('output_records.json', 'r') as f:
    json_content = f.read()

print(json_content)
Output
[{"name":"Alice","age":25,"city":"NY"},{"name":"Bob","age":30,"city":"LA"}]
⚠️

Common Pitfalls

Common mistakes when writing JSON with pandas include:

  • Not specifying orient correctly, which can lead to unexpected JSON structure.
  • Forgetting to set lines=True when writing newline-delimited JSON, causing parsing errors in some tools.
  • Assuming to_json() writes to a file by default; it returns a string if no file path is given.
python
import pandas as pd

data = {'a': [1, 2], 'b': [3, 4]}
df = pd.DataFrame(data)

# Wrong: expecting file but no path given
json_str = df.to_json()  # returns string, does not write file

# Right: write to file

df.to_json('output.json')

# Wrong: forgetting lines=True for newline JSON
# df.to_json('output_lines.json', orient='records')  # This writes one big JSON array

# Right: use lines=True

df.to_json('output_lines.json', orient='records', lines=True)
📊

Quick Reference

ParameterDescriptionCommon Values
path_or_bufFile path or buffer to write JSON. If None, returns JSON string.None or 'filename.json'
orientFormat of JSON output.'columns', 'records', 'index', 'split', 'values'
linesWrite JSON as newline-delimited records.True or False

Key Takeaways

Use DataFrame.to_json() to write JSON from pandas.
Specify a file path in to_json() to write directly to a file.
Choose the orient parameter to control JSON structure.
Set lines=True for newline-delimited JSON format.
Without a file path, to_json() returns a JSON string.