Download Button - local json file

streamlit version 1.12.2
python version 3.9.13

Hey Streamlit Community - I am attempting to use the download_button component, but not quite sure how the “data” accepts a “file” value. I see from the docs that a file can be submitted as the data, and I have a file that was generated and available in the same directory.

Any thoughts on what I may be missing or how to approach this?

with open('data.jsonl', 'w') as jsonfile:
	for line in data_list:
	    jsonfile.write(json.dumps(line)+'\n')
	st.download_button(label="Download JSON", data=jsonfile, file_name='data.jsonl', mime='application/json')

Additionally, I’ve tried to 1) include a “path” to the file 2) put the path as a string, and 3) insert the jsonlife variable as shown above as the data source. Any guidance would be appreciated. Thanks

Since you’re using a text-based file type, you can just pass the data directly as a string, like this:

import streamlit as st

data = [
    {"name": "John", "age": 20},
    {"name": "Jane", "age": 21},
    {"name": "Jack", "age": 22},
]

# Add button to download as jsonl

st.download_button(
    "Download as jsonl",
    data="\n".join([str(d) for d in data]),
    file_name="output.jsonl",
    mime="application/jsonl",
)

Alternatively, if you already have it in a file, you can just read the file and pass that as the data.

from pathlib import Path

st.download_button(
    "Download from file",
    data=Path("output.jsonl").read_text(),
    file_name="output.jsonl",
    mime="application/jsonl",
)
1 Like

Thank you!! Worked perfectly

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.