Python Pandas DataFrame to JSON: Error 'Object of type DataFrame is not JSON serializable' and Solution
The error message 'Object of type DataFrame is not JSON serializable' typically occurs when you try to convert a pandas DataFrame object directly into a JSON format using the json library's dumps() function.
The dumps() function from the json library is used to serialize Python objects into a JSON formatted string. However, DataFrame objects from the pandas library cannot be directly serialized as they contain complex data structures and are not standard JSON types.
To resolve this issue, you can convert the DataFrame to a format that can be serialized to JSON, such as a dictionary or a list of dictionaries, and then use the json.dumps() function to convert it to a JSON formatted string.
Here's an example of how you can convert a DataFrame to a list of dictionaries and then serialize it to JSON:
import pandas as pd
import json
# Create a sample DataFrame
df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
# Convert DataFrame to a list of dictionaries
data = df.to_dict('records')
# Serialize the data to JSON
json_data = json.dumps(data)
print(json_data)
This will convert the DataFrame into a JSON formatted string that can be serialized.
原文地址: https://www.cveoy.top/t/topic/p35q 著作权归作者所有。请勿转载和采集!