Write an app that takes in a json file and visualizes what it can.
To upload files, please first save the app
import streamlit as st
import json
import pandas as pd
import plotly.express as px
st.title("JSON Viewer & Visualizer")
# File uploader
uploaded_file = st.file_uploader("Choose a JSON file", type="json")
if uploaded_file is not None:
try:
# Load JSON data
data = json.load(uploaded_file)
# Show raw JSON
with st.expander("Raw JSON Data"):
st.json(data)
# Try to convert to DataFrame if possible
try:
if isinstance(data, list):
df = pd.json_normalize(data)
elif isinstance(data, dict):
# If it's a nested dictionary, try to flatten it
df = pd.json_normalize(data)
st.subheader("Data Table View")
st.dataframe(df)
# Get numeric columns for visualization
numeric_cols = df.select_dtypes(include=['float64', 'int64']).columns
if len(numeric_cols) > 0:
st.subheader("Visualizations")
# Select columns for visualization
x_col = st.selectbox("Select X-axis", df.columns)
y_col = st.selectbox("Select Y-axis", numeric_cols)
# Chart type selector
chart_type = st.selectbox(
"Select Chart Type",
["Scatter", "Line", "Bar", "Box"]
)
# Create visualization based on selection
if chart_type == "Scatter":
fig = px.scatter(df, x=x_col, y=y_col)
elif chart_type == "Line":
fig = px.line(df, x=x_col, y=y_col)
elif chart_type == "Bar":
fig = px.bar(df, x=x_col, y=y_col)
else: # Box plot
fig = px.box(df, x=x_col, y=y_col)
st.plotly_chart(fig)
except Exception as e:
st.warning("Could not convert JSON to DataFrame for visualization. " +
"The JSON structure might be too complex or nested.")
st.error(f"Error: {str(e)}")
except Exception as e:
st.error(f"Error reading JSON file: {str(e)}")
else:
st.info("Please upload a JSON file to begin visualization.")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?