You should just be able to use Pandas as follows:

import pandas as pd

with open('PeshVsQuetta.json', encoding='utf-8-sig') as f_input:
    df = pd.read_json(f_input)

df.to_csv('PeshVsQuetta.csv', encoding='utf-8', index=False)

This assumes that your JSON file contains a BOM at the start. For the data you have given above, this produces the following CSV file:

date_time,tweet_content,tweet_id,user_id
2018-03-20 18:38:35,RT @PTISPOfficial: پاکستان تحریک انصاف کے وائس چیئرمین شاہ محمود قریشی  بغیر کسی پروٹوکول کے پاکستان سپر لیگ کا میچ دیکھنے کے لئے اسٹیڈیم م…,976166125502427136,938118866135343104
2018-03-20 18:38:35,"At last, Pakistan Have Witnessed The Most Thrilling Match Of Cricket In Pakistan, The Home. 

#PZvQG 
#ABC",976166125535973378,959235642
2018-03-20 18:38:35,"RT @thePSLt20: SIX! 19.4 Liam Dawson to Anwar Ali
Watch ball by ball highlights at (link removed)

#PZvQG #HBLPSL #PSL2018 @_crici…",976166126202839040,395163528
2018-03-20 18:38:35,RT @JeremyMcLellan: Rumor has it Amir Liaquat isn’t allowed to play in #PSL2018 because he keeps switching teams every week.,976166126483902466,3117825702
2018-03-20 18:38:35,RT @daniel86cricket: Peshawar beat Quetta by 1 run in one of the best T20 thrillers. PSL played in front of full house in Lahore Pakistan i…,976166126559354880,3310967346
2018-03-20 18:38:35,"I wanted a super over😭
#PZvQG",976166126836178944,701494826194354179
2018-03-20 18:38:35,RT @hinaparvezbutt: Congratulations Peshawar Zalmi over great win but Quetta Gladiators won our hearts ♥️  #PZvQG,976166126685171713,347132028
2018-03-20 18:38:35,"RT @walterMiitty: It's harder than I thought to tell the truth
It's gonna leave you in pieces
All alone with your demons
And I know that we…",976166126924201986,3461853618

Note: some of your fields contain newlines, so the output might look a bit odd. An application reading this though will handle it correctly (as long as you tell it the encoding is UTF-8 when importing it)

Answer from Martin Evans on Stack Overflow
🌐
BMC Software
bmc.com › blogs › pandas-read-json-csv-files
Pandas: How To Read CSV & JSON Files – BMC Software | Blogs
November 20, 2020 - Below we read a .csv file: import pandas as pd url = 'https://raw.githubusercontent.com/werowe/logisticRegressionBestModel/master/KidCreative.csv' df = pd.read_csv(url, delimiter=',') ... The results look like this.
🌐
GitHub
gist.github.com › luisfredgs › a3bef4f65f166d3824eef182685004c1
Convert pandas dataframe from CSV to JSON · GitHub
Download ZIP · Convert pandas dataframe from CSV to JSON · Raw · pandas_csv_to_json.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Discussions

Download a csv from url and make it a dataframe python pandas - Stack Overflow
I am new to python so need a little help here. I have a dataframe with a url column with a link that allows me to download a CSV for each link. My aim is to create a loop/ whatever works so that I ... More on stackoverflow.com
🌐 stackoverflow.com
How to download .csv file, produced by pandas df, on click of a simple button?
You can't set the download folder from Python code, that's a browser thing. You also can't return a string in this case you need to return a Response object: https://flask.palletsprojects.com/en/2.3.x/api/#response-objects This may also be helpful: https://flask.palletsprojects.com/en/2.3.x/api/#flask.make_response response = make_response(df.to_csv(pth)) response.headers["Content-Disposition"] = "attachment; filename=export.csv" response.headers["Content-type"] = "text/csv" response output I've never used it but this may be the most direct means: https://flask.palletsprojects.com/en/2.3.x/api/#flask.send_file there is also https://flask.palletsprojects.com/en/2.3.x/api/#flask.send_from_directory if the file is on disk already. You don't have to write the file to disk, you can use one of the above options with binary data, but I'm not familiar enough with pandas to say how to do that. More on reddit.com
🌐 r/flask
4
3
May 26, 2023
python - Download csv file and convert to JSON - Stack Overflow
I would like to write Python script that download csv file from URL and then return this in JSON. The problem is that I need execute it as fast as it possible. What is the best way to do it? I was More on stackoverflow.com
🌐 stackoverflow.com
python - Using Pandas to convert csv to Json - Stack Overflow
I want to convert a CSV to a JSON format using pandas. I am a tester and want to send some events to Event Hub for that I want to maintain a CSV file and update my records/data using the CSV file. I More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 1
7

You should just be able to use Pandas as follows:

import pandas as pd

with open('PeshVsQuetta.json', encoding='utf-8-sig') as f_input:
    df = pd.read_json(f_input)

df.to_csv('PeshVsQuetta.csv', encoding='utf-8', index=False)

This assumes that your JSON file contains a BOM at the start. For the data you have given above, this produces the following CSV file:

date_time,tweet_content,tweet_id,user_id
2018-03-20 18:38:35,RT @PTISPOfficial: پاکستان تحریک انصاف کے وائس چیئرمین شاہ محمود قریشی  بغیر کسی پروٹوکول کے پاکستان سپر لیگ کا میچ دیکھنے کے لئے اسٹیڈیم م…,976166125502427136,938118866135343104
2018-03-20 18:38:35,"At last, Pakistan Have Witnessed The Most Thrilling Match Of Cricket In Pakistan, The Home. 

#PZvQG 
#ABC",976166125535973378,959235642
2018-03-20 18:38:35,"RT @thePSLt20: SIX! 19.4 Liam Dawson to Anwar Ali
Watch ball by ball highlights at (link removed)

#PZvQG #HBLPSL #PSL2018 @_crici…",976166126202839040,395163528
2018-03-20 18:38:35,RT @JeremyMcLellan: Rumor has it Amir Liaquat isn’t allowed to play in #PSL2018 because he keeps switching teams every week.,976166126483902466,3117825702
2018-03-20 18:38:35,RT @daniel86cricket: Peshawar beat Quetta by 1 run in one of the best T20 thrillers. PSL played in front of full house in Lahore Pakistan i…,976166126559354880,3310967346
2018-03-20 18:38:35,"I wanted a super over😭
#PZvQG",976166126836178944,701494826194354179
2018-03-20 18:38:35,RT @hinaparvezbutt: Congratulations Peshawar Zalmi over great win but Quetta Gladiators won our hearts ♥️  #PZvQG,976166126685171713,347132028
2018-03-20 18:38:35,"RT @walterMiitty: It's harder than I thought to tell the truth
It's gonna leave you in pieces
All alone with your demons
And I know that we…",976166126924201986,3461853618

Note: some of your fields contain newlines, so the output might look a bit odd. An application reading this though will handle it correctly (as long as you tell it the encoding is UTF-8 when importing it)

🌐
GeeksforGeeks
geeksforgeeks.org › convert-csv-to-json-using-python
Convert CSV to JSON using Python - GeeksforGeeks
April 28, 2025 - Explanation: This code reads a CSV file into a pandas DataFrame using pd.read_csv. It then converts the DataFrame into a list of JSON objects (one per row) using to_json with orient='records' and lines=True, saving each JSON object on a new line in the output file.
🌐
Like Geeks
likegeeks.com › home › python › pandas › convert csv to json using python pandas (easy tutorial)
Convert CSV to JSON using Python Pandas (Easy Tutorial)
December 11, 2023 - In this tutorial, We’ll learn how to convert CSV files to JSON, including reading CSV files, converting the entire DataFrame as well as specific columns or rows to JSON. We’ll use Pandas read_csv() and Pandas to_json() to do this.
🌐
Verpex
verpex.com › blog › website-tips › how-to-convert-json-to-csv-in-python
How to Convert JSON to CSV in Python
This involves making sure that each key in the JSON object becomes a column in the CSV file, while each value becomes a row entry. ... Once the data is in tabular format, you can write it into the CSV file. This file can then be opened in tools like Excel or imported into a database for further analysis. ... import pandas as pd import json json_data = '[{"name": "Alice", "age": 30, "city": "New York"}, {"name": "Bob", "age": 25, "city": "Los Angeles"}, {"name": "Charlie", "age": 35, "city": "Chicago"}]' data = json.loads(json_data) df = pd.DataFrame(data) df.to_csv('users.csv', index=False)
Find elsewhere
🌐
Reddit
reddit.com › r/flask › how to download .csv file, produced by pandas df, on click of a simple button?
r/flask on Reddit: How to download .csv file, produced by pandas df, on click of a simple button?
May 26, 2023 -

I am learning web dev with flask. So far I have loved flask with its simplistic framework, Django was taking too much of my time especially since I don't main web development.

Please help me understand why I can't download my dataframe to csv using the view function in flask.

My flask app for creating an output.csv from a simple dataframe - df = pd.DataFrame({"id":[1,2,3],"name":['x','y','z']}).

Issues:

  • Linux has / whilst windows uses . How would I account for this exactly when choosing a download folder?

  • Is there a way to dynamically set a downloads folder based on the client's computer?

  • Must the view function always return a string? I am getting the error TypeError: The view function for 'show_data' did not return a valid response. The function either returned None or ended without a return statement.

One last confusion on "downloads":

  • I have scoured through several download and upload tutorials on flask. For download, does the file actually need to exist on server, unlike producing one from pandas?

#./df_to_csv.py
from flask import *
import pandas as pd
from tkinter import filedialog as fd

app = Flask(__name__)

@app.route('/')
def open_page():
    return render_template('btn.html')

@app.route('/get_data',methods=['GET','POST'])
def show_data():
    if request. Method == 'POST':
        f = './df_output.csv'
        df = pd.DataFrame({"id":[1,2,3],"name":['x','y','z']})
        # df.to_csv(f"{f}")
        pth = fd.askdirectory() + "/test.csv"
        return df.to_csv(pth)

if __name__ == '__main__':
    app.run(debug=True)

Here is my corresponding simple html form:

<!-- ./templates/btn.html -->

<form action="http://localhost:5000/get_data"
method="post"
enctype="multipart/form-data"
>
<input type="submit" value="Download">
</form>

Many thanks for your guidance.
Top answer
1 of 2
2
You can't set the download folder from Python code, that's a browser thing. You also can't return a string in this case you need to return a Response object: https://flask.palletsprojects.com/en/2.3.x/api/#response-objects This may also be helpful: https://flask.palletsprojects.com/en/2.3.x/api/#flask.make_response response = make_response(df.to_csv(pth)) response.headers["Content-Disposition"] = "attachment; filename=export.csv" response.headers["Content-type"] = "text/csv" response output I've never used it but this may be the most direct means: https://flask.palletsprojects.com/en/2.3.x/api/#flask.send_file there is also https://flask.palletsprojects.com/en/2.3.x/api/#flask.send_from_directory if the file is on disk already. You don't have to write the file to disk, you can use one of the above options with binary data, but I'm not familiar enough with pandas to say how to do that.
2 of 2
1
Hi, in my current website I convert data from db to json and create option to download it. You can try to change it to csv format. I have in flask api endpoint which returns return jsonify(results_data), 200 where result_data is dict. in js I have this: async function loadResults(){ return await (fetch('/api/get_results/', {method: "GET"})); } get buton by id button.addEventListener('click', async () =>{ let response = []; const downloadLink = some 'a' tag try{ response = await loadResults(); } catch (e){ console.log(e) } const results = await response.json(); const blob = new Blob([JSON.stringify(results, null, 2)], { type: 'application/json' }); downloadLink.href = URL.createObjectURL(blob); downloadLink.download = 'data.json'; downloadLink.textContent = 'Download JSON'; downloadLink.style.display = 'block'; });
Top answer
1 of 1
1

I tried comparing your conversion process with pandas and used this code:

import io
import pandas as pd
import requests
import json
import csv
import time

r_bytes = requests.get("https://www.stats.govt.nz/assets/Uploads/Annual-enterprise-survey/Annual-enterprise-survey-2020-financial-year-provisional/Download-data/annual-enterprise-survey-2020-financial-year-provisional-csv.csv").content
print("finished download")
r = r_bytes.decode('utf8')
print("finished decode")

start_df_timestamp = time.time()
df = pd.read_csv(io.StringIO(r), sep=";")
result_df = json.dumps(df.to_dict('records'))
end_df_timestamp = time.time()
print("The df method took {d_t}s".format(d_t=end_df_timestamp-start_df_timestamp))


start_csv_reader_timestamp = time.time()
reader = csv.DictReader(io.StringIO(r))
result_csv_reader = json.dumps(list(reader))
end_csv_reader_timestamp = time.time()
print("The csv-reader method took {d_t}s".format(d_t=end_csv_reader_timestamp-start_csv_reader_timestamp))

and the result was:

finished download
finished decode
The df method took 0.200181245803833s
The csv-reader method took 0.3164360523223877s

this was using a random 37k row CSV file and i noticed that downloading it was by far the most time-intensive thing to do. Even if the the pandas.df functions were faster for me, you should probably try to profile your code, to see whether the conversion really is significantly adding to your runtime. :-)

PS: If you need to constantly monitor the CSV and processing updates turns out to be time-intensive, you could use hashes to only process alterations if the CSV has changed since your last download.

🌐
W3Schools
w3schools.com › python › pandas › pandas_csv.asp
Pandas Read CSV
Pandas HOME Pandas Intro Pandas Getting Started Pandas Series Pandas DataFrames Pandas Read CSV Pandas Read JSON Pandas Analyzing Data · Cleaning Data Cleaning Empty Cells Cleaning Wrong Format Cleaning Wrong Data Removing Duplicates ... A simple way to store big data sets is to use CSV files (comma separated files). CSV files contains plain text and is a well know format that can be read by everyone including Pandas. In our examples we will be using a CSV file called 'data.csv'. Download data.csv.
🌐
McNeel Forum
discourse.mcneel.com › scripting
Converting JSON to CSV - Scripting - McNeel Forum
March 14, 2024 - Hi, i’m trying to convert JSON to CSV. So far i have the following code, which i mostly found here. #! python3 # r: numpy, pandas, json import rhinoscriptsyntax as rs import pandas as pd import json as json # Reading JSON data from a file with open("data.json") as f: json_data = json.load(f) # Converting JSON data to a pandas DataFrame df = pd.read_json(json_data) # Writing DataFrame to a CSV file df.to_csv("output.csv", index=False) It throws up the error: Error building code | Err...
🌐
alpharithms
alpharithms.com › home › tutorials › convert json to csv in python
Convert JSON to CSV in Python - αlphαrithms
July 7, 2022 - Among the many convenient methods ... in the Pandas library is the to_json method. This method, found in the DataFrame class, is a powerful tool for converting data from CSV to JSON.
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-json-to-csv-in-python
Convert JSON to CSV in Python - GeeksforGeeks
July 12, 2025 - Explanation: This code reads a JSON file (data.json), extracts the emp_details list, and writes it into a CSV file (data_file.csv). It writes the headers (keys) from the first employee and then appends the employee details (values) as rows in the CSV.
🌐
Steve's Data Tips and Tricks
spsanderson.com › steveondata › posts › 2025-10-01
Working with CSV Files and JSON Data in Python – Steve’s Data Tips and Tricks
October 1, 2025 - Learn how to read, write, and convert CSV and JSON files in Python with beginner friendly examples. This guide covers practical code snippets, tips for using the csv and json modules, and a hands on activity to help you master data handling in Python.