[python] python exports json string to excel | pandas processes json string and saves it as csv

How to convert json to csv

1. Convert json directly to csv

In Python, you can use the pandas library to process DataFrames and convert JSON data to CSV format. Below is a simple sample code that shows how to convert JSON data to a CSV file using the pandas library:

import pandas as pd

# 示例JSON数据
json_data = [
    {
    
    "name": "Alice", "age": 25, "city": "New York"},
    {
    
    "name": "Bob", "age": 30, "city": "San Francisco"},
    {
    
    "name": "Charlie", "age": 22, "city": "Los Angeles"}
]

# 将JSON数据加载到DataFrame
df = pd.DataFrame(json_data)

# 将DataFrame保存为CSV文件
csv_filename = "output.csv"
df.to_csv(csv_filename, index=False)

print("JSON数据已转换为CSV文件:", csv_filename)

Insert image description here

2. Continue to append json to csv

Notice:

  • The latest version of pandas is used here

If you want new JSON data to be added to the same CSV file on each execution, rather than overwriting previous data, you need to load the CSV file on each execution and then append the new JSON data to the existing CSV in the file. The following is a modified code example that appends the JSON data for each execution to the same CSV file:

import pandas as pd

# 示例JSON数据
json_data = [
    {
    
    "name": "David", "age": 28, "city": "Chicago"},
    {
    
    "name": "Eve", "age": 33, "city": "Seattle"},
    {
    
    "name": "Frank", "age": 40, "city": "Boston"}
]

# CSV文件名
csv_filename = "output.csv"

try:
    # 尝试加载已有的CSV文件
    df = pd.read_csv(csv_filename)
except FileNotFoundError:
    # 如果文件不存在,创建一个新的DataFrame
    df = pd.DataFrame()

# 将新的JSON数据加载到DataFrame
new_data = pd.DataFrame(json_data)
df = pd.concat([df, new_data], ignore_index=True)

# 将DataFrame保存回CSV文件
df.to_csv(csv_filename, index=False)

print("新的JSON数据已追加到CSV文件:", csv_filename)

This version of the code uses the concat method to append new JSON data to an existing DataFrame. This method can accept a list containing the DataFrames to be joined. The ignore_index=True parameter ensures that the resulting DataFrame is re-indexed to avoid index conflicts. Then save the entire DataFrame back into the same CSV file. This way, every time the code is executed, new JSON data will be added to the same CSV file without overwriting the previous data.

Guess you like

Origin blog.csdn.net/wanglei19891210/article/details/132223341