Exporting data to JSON helps you save and share data in a simple, readable format that many programs understand.
Exporting to JSON in Data Analysis Python
DataFrame.to_json(path_or_buf=None, orient='columns', lines=False)
path_or_buf: File path or buffer to write the JSON data. If None, returns JSON string.
orient: Format of JSON string. Common options: 'columns' (default), 'records', 'index'.
df.to_json('data.json')json_str = df.to_json()
df.to_json('data_records.json', orient='records')
This program creates a small table of names and ages, saves it as a JSON file in 'records' format, then reads and prints the JSON content.
import pandas as pd # Create a simple DataFrame data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]} df = pd.DataFrame(data) # Export DataFrame to JSON file json_file = 'people.json' df.to_json(json_file, orient='records') # Read the JSON file back to verify with open(json_file, 'r') as file: content = file.read() print(content)
Using orient='records' creates a list of JSON objects, which is easy to read and use in many applications.
If you don't provide a file path, to_json() returns the JSON string instead of saving a file.
Make sure to handle file paths carefully to avoid overwriting important files.
Exporting to JSON saves your data in a widely used, easy-to-share format.
You can save directly to a file or get a JSON string to use in your program.
Choosing the right orient option helps match the JSON format to your needs.