Сохранение и добавление ответов API в файлы JSON в Python

Чтобы сохранить ответ API в файл JSON и добавить его, вы можете использовать различные методы Python. Вот несколько вариантов:

Метод 1: использование модуля jsonи функции open()

import json
# Assume `response` is the API response data
response_data = {"key": "value"}
# Read existing data from the JSON file
with open("data.json", "r") as file:
    existing_data = json.load(file)
# Append the new response data to the existing data
existing_data.append(response_data)
# Write the updated data back to the JSON file
with open("data.json", "w") as file:
    json.dump(existing_data, file)

Метод 2. Использование библиотеки jsonlines

import jsonlines
# Assume `response` is the API response data
response_data = {"key": "value"}
# Append the response data to the JSON file
with jsonlines.open("data.jsonl", mode='a') as writer:
    writer.write(response_data)

Метод 3. Использование библиотеки pandas

import pandas as pd
# Assume `response` is the API response data
response_data = {"key": "value"}
# Read existing data from the JSON file as a DataFrame
df = pd.read_json("data.json")
# Convert the response data to a DataFrame
response_df = pd.DataFrame(response_data, index=[0])
# Append the response DataFrame to the existing data
df = pd.concat([df, response_df], ignore_index=True)
# Write the updated data back to the JSON file
df.to_json("data.json", orient="records")