From a list/dict to ready-to-download file

Hi,

I’ve built a chat using these principles.

I added a button to allow users to download their conversation:

To do so, I save the conversation as a temporary JSON file (using json.dump) and then use it with st.download_button.

But is there a way to bypass the temporary file? :thinking:

import json
import streamlit as st

messages = [{"role": "user", "content": "Hello Streamlit"},
                     {"role": "assistant", "content": "Hello!"}]

file_path = "./tmp.json"

with open(file_path, 'w') as file:
    json.dump(messages, file)

with open(file_path, "rb") as file:
    st.download_button(label="📥 Save this conversation!",
                       data=file,
                       file_name="conversation.json",
                       mime="application/json")
import json
import streamlit as st


messages = [
    {"role": "user", "content": "Hello Streamlit"},
    {"role": "assistant", "content": "Hello!"}
]


def download_json(data):
    json_data = json.dumps(data)
    json_bytes = json_data.encode('utf-8')
    
    return json_bytes


st.download_button(
    label="📥 Save this conversation!",
    data=download_json(messages),
    file_name="conversation.json",
    mime='application/json'
)
2 Likes

Thanks @ferdy, this is the trick I was looking for… and I think there are some other apps I could potentially clean as well using it! :pray:

1 Like

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