athene-70b-0725· unknown
LMArena Human Preference 100K
output a duckdb table to a json file in python
- User
output a duckdb table to a json file in python
- Assistant
Here's a concise way to output a DuckDB table to a JSON file in Python:
import duckdb import json # assume 'con' is your DuckDB connection and 'table_name' is the table you want to export con = duckdb.connect(database=':memory:') # or a file-based database table_name = 'my_table' # Fetch the table data as a Pandas DataFrame (efficient and convenient) df = con.execute(f"SELECT * FROM {table_name}").fetchdf() # Convert the DataFrame to JSON and write to file with open(f"{table_name}.json", 'w') as f: json.dump(df.to_dict(orient='records'), f, indent=4) # pretty-print with indent=4 print(f"Table {table_name} exported to {table_name}.json")