Assistance Needed with JSON Content Not Displaying in Streamlit App

Hello,

I am experiencing an issue with my Streamlit application where I am unable to view the contents of an uploaded JSON file. Upon uploading the file, the application does not display the JSON data as expected. Here is the code snippet used for the upload and display functionality:

import streamlit as st
import json

if st.button("Enter your Json Data"):
    with st.container():
        option = st.radio("Do you want to upload a JSON file?", ("Yes", "No"))
        if option == "Yes":
            uploaded_file = st.file_uploader("Choose a JSON file", type="json")
            if uploaded_file is not None:
                # Read the file and convert to JSON
                input_data = json.load(uploaded_file)
                # Use st.session_state to cache the data
                st.session_state['json_data'] = input_data
                st.json(input_data)
            else:
                st.warning("Please upload a JSON file.")
        else:
            if 'json_data' in st.session_state:
                # Display the cached JSON data
                st.json(st.session_state['json_data'])
            else:
                st.warning("No JSON data uploaded yet.")

# You must check outside of the button press event if the session state has data to show it persistently.
if 'json_data' in st.session_state:
    st.json(st.session_state['json_data'])

Despite the upload, the JSON content is not rendered. The issue persists with no error messages indicating what may be going wrong. Could you provide some guidance on how to troubleshoot or correct this problem so that the JSON data displays correctly after being uploaded?

Thank you for your assistance.

Let me explain with a sample image and a sample scenario.

The story

  • Let us start at num1. We press the button.
  • Streamlit will then reread the code starting at line 1 specifically at num2. Continue reading at lines 2, 3, 4, 5.
  • Once it reaches reading at line 5, it is able to continue because the btn state is true (for once).
  • It will read num3, num4, num5 (assuming hitting yes) and num6.
  • After hitting num6 (including user action of uploading a file) streamlit will reread again starting at line 1, we are now at num7 and continue reading at lines 2, 3, 4 and 5 we are now at num8. Hey the btn state is now false so we cannot enter on line 6 again. It will continue to read lines 24, 25, 26 and 27.
  • At line 27 there is still no json_data in session state, so line 28 is not read.

This is the reason why we got no chance of seeing the uploaded file (although the upload is successful) because we are blocked by that amazing button.

Streamlit has explained the button in one of their documentations. Streamlit’s main concepts are also there.

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