PROJECT OVERVIEW:
The goal is to create a single-page web application (SPA) that serves as a fast, interactive, and user-friendly alternative to command-line tools like `jq` for querying and manipulating JSON data. The application will be optimized for performance, especially with large JSON files, by leveraging efficient parsing and querying techniques. The core value proposition is to provide developers, data analysts, and engineers with a visually intuitive and highly responsive tool to explore, filter, transform, and extract data from JSON structures directly within their web browser, without needing to install or manage local command-line utilities.
TECH STACK:
- Frontend Framework: React (using functional components and hooks)
- Styling: Tailwind CSS for rapid UI development and utility-first styling.
- State Management: Zustand for simple and efficient global state management. For more complex states if needed, consider `useReducer` or Context API.
- JSON Parsing: `JSON.parse` for standard parsing, potentially exploring optimized libraries like `json5` or WASM-based parsers if performance bottlenecks are identified during development for extremely large files.
- Query Engine: Implement a custom query engine inspired by `jq`'s capabilities but adapted for a web environment. Focus on DFA-based or similar efficient matching algorithms if `jq`'s performance is the primary benchmark. Alternatively, leverage existing JavaScript libraries for JSON path queries (`jsonpath-plus`) and optimize their usage or build a higher-level abstraction.
- Other Libraries: `react-beautiful-dnd` (or similar) for potential future drag-and-drop features, `react-syntax-highlighter` for code/query highlighting, potentially a WASM module for CPU-intensive tasks if necessary.
CORE FEATURES:
1. **JSON File Upload/Input**:
* **User Flow**: User clicks an 'Upload File' button or a 'Paste JSON' textarea.
* For file upload, a native file dialog appears. Upon selection, the file content is read using the FileReader API.
* For pasting, a large textarea allows direct input of JSON.
* A loading state is displayed during file reading/parsing.
* Upon successful parsing, the JSON data is stored in the application's state and a confirmation message is shown.
* Error handling for invalid JSON format (e.g., `SyntaxError` from `JSON.parse`) should display a user-friendly error message.
2. **Interactive Query Interface**:
* **User Flow**: A dedicated input area (e.g., a `textarea` with syntax highlighting) for the query.
* A query language inspired by `jq` (e.g., `.users[] | select(.age > 30) | .name`) will be supported.
* Real-time query validation: As the user types, basic syntax errors can be highlighted.
* A 'Run Query' button triggers the processing.
* Alternatively, an 'Auto-Run' toggle can process queries as the user types (debounced to avoid excessive processing).
3. **Fast Query Execution & Results Display**:
* **User Flow**: After a query is executed, the application processes the stored JSON data using the entered query.
* The results are displayed in a structured, collapsible tree view (like browser dev tools) or as a formatted JSON/table view.
* Performance is key: For large datasets, implement efficient iteration and filtering. If using a library, ensure it's optimized. Consider WASM for computationally intensive query logic if plain JS is too slow.
* Displaying results should also handle empty results gracefully (e.g., 'No results found').
* A loading indicator should be shown during query execution.
4. **Download Results**:
* **User Flow**: A 'Download Results' button is available next to the results display.
* Clicking the button prompts the user to download the displayed results as a JSON file.
* The filename can be dynamically generated (e.g., `query-results-timestamp.json`).
5. **Query History & Management**:
* **User Flow**: A sidebar or dropdown lists previously used queries.
* Users can click a past query to load it into the query input area.
* Option to save current query with a name.
* MVP might limit history to local storage for a session or a small number of recent queries.
UI/UX DESIGN:
- **Layout**: A three-column layout is recommended:
1. Left Sidebar: For query history, saved queries, and potentially input file info/name.
2. Main Content Area (Top): JSON input/upload controls and the query input textarea.
3. Main Content Area (Bottom): Results display (tree view, table, or raw JSON).
- **Color Palette**: Clean, modern, and developer-focused. Use a dark theme option. Primary colors: Deep blues, grays, subtle accent colors (e.g., a vibrant teal or purple for interactive elements and highlights). Use sparingly.
- **Typography**: Monospace font (e.g., 'Fira Code', 'Source Code Pro') for code/JSON/query areas. Sans-serif font (e.g., 'Inter', 'Roboto') for UI elements and labels.
- **Responsive Design**: The layout should adapt gracefully to different screen sizes. On smaller screens, columns might stack vertically or become collapsible/modal panels. Ensure touch-friendliness.
- **Visual Feedback**: Use subtle animations for loading states, transitions between states, and hover effects on interactive elements.
COMPONENT BREAKDOWN:
- `App.js`: Main application component, sets up layout and routing (if needed, though likely a single page).
- `Header.js`: Top navigation bar (App title, maybe global actions).
- `Sidebar.js`: Contains `QueryHistoryList.js`, `SavedQueries.js`.
- `QueryHistoryList.js`: Renders a list of past queries.
- `QueryHistoryItem.js`: Represents a single item in the history list.
- `InputPanel.js`: Contains `JsonUploader.js` and `QueryInput.js`.
- `JsonUploader.js`: Handles file input (`<input type='file'>`) and drag-and-drop functionality, uses `FileReader` API.
- `QueryInput.js`: `textarea` with syntax highlighting (`react-syntax-highlighter`) for query input, handles input changes and debouncing.
- `ResultsPanel.js`: Displays query results using `JsonTreeView.js` or `ResultsTable.js`.
- `JsonTreeView.js`: Recursively renders JSON data in a collapsible tree format.
- `ProgressBar.js`: Visual indicator for loading or processing states.
- `Button.js`, `Input.js`, `Textarea.js`, `Modal.js`: Reusable UI components.
Props examples:
- `JsonUploader`: `onFileLoad: (jsonData: object | array) => void`, `onError: (error: string) => void`
- `QueryInput`: `value: string`, `onChange: (query: string) => void`, `onRunQuery: () => void`, `isLoading: boolean`
- `JsonTreeView`: `data: object | array`
- `Sidebar`: `queries: Array<{id: string, query: string, name?: string}>`, `onSelectQuery: (query: string) => void`
DATA MODEL:
- `appState` (using Zustand store):
* `jsonData`: `object | array | null` (The parsed JSON data from the input).
* `query`: `string` (The current query string).
* `results`: `object | array | null` (The data after applying the query).
* `isLoading`: `boolean` (Global loading state for file parsing or query execution).
* `error`: `string | null` (Stores any error messages).
* `queryHistory`: `Array<{id: string, query: string, timestamp: number}>` (List of past queries).
* `savedQueries`: `Array<{id: string, query: string, name: string}>` (User-saved queries).
- **Mock Data Format**: Mock data should represent typical JSON structures, including nested objects, arrays, various data types (strings, numbers, booleans, null).
```json
// Example Mock Data
{
"users": [
{
"id": 1,
"name": "Alice",
"age": 30,
"isActive": true,
"address": {
"street": "123 Main St",
"city": "Anytown"
}
},
{
"id": 2,
"name": "Bob",
"age": 24,
"isActive": false,
"tags": ["dev", "frontend"]
}
],
"settings": {
"theme": "dark",
"notifications": {
"email": true,
"sms": false
}
}
}
```
ANIMATIONS & INTERACTIONS:
- **Loading States**: Use spinners (`<ProgressBar>`) or subtle skeleton loaders when parsing files or executing queries. The entire results area could fade out slightly while loading.
- **Transitions**: Smooth transitions when showing/hiding collapsed sections in the JSON tree view. Fade-in/fade-out animations when switching between different views or when errors appear/disappear.
- **Hover Effects**: Subtle background color changes or slight scaling on interactive elements like buttons, list items in history, and expandable nodes in the tree view.
- **Micro-interactions**: Visual feedback when a query is successfully executed (e.g., a brief confirmation message or a subtle animation on the 'Run Query' button).
EDGE CASES:
- **Empty JSON Input**: Handle cases where the user inputs an empty string or uploads an empty file. Display a clear message.
- **Invalid JSON**: Catch `SyntaxError` during `JSON.parse`. Display a user-friendly error message indicating the problem and potentially the line number if the parser provides it.
- **Invalid Query**: Implement basic query syntax validation. If the query is malformed, provide feedback in the query input area or via an error message. Decide whether to throw an error or return an empty result set for syntactically valid but logically incorrect queries.
- **Large Files**: For files exceeding browser memory limits (e.g., >1GB), consider strategies like streaming parsing (if a library supports it) or informing the user about limitations and recommending CLI tools for such cases. The initial MVP might focus on files up to a few hundred MB.
- **Empty Results**: If a query returns no matches, display a clear 'No results found.' message instead of an empty structure.
- **Accessibility (a11y)**: Use semantic HTML elements. Ensure keyboard navigation is fully supported. Provide ARIA attributes where necessary, especially for interactive elements and dynamic content updates. Ensure sufficient color contrast.
- **State Persistence**: Use `localStorage` to persist the query history and potentially the last used query and JSON input across sessions.
SAMPLE DATA:
```json
// Sample 1: User List
{
"users": [
{"id": 1, "name": "Alice", "email": "alice@example.com", "roles": ["admin", "editor"]},
{"id": 2, "name": "Bob", "email": "bob@example.com", "roles": ["viewer"]},
{"id": 3, "name": "Charlie", "email": "charlie@example.com", "roles": ["editor"]}
]
}
// Sample 2: Product Catalog
{
"products": [
{"sku": "A123", "name": "Laptop", "price": 1200, "tags": ["electronics", "computers"]},
{"sku": "B456", "name": "Keyboard", "price": 75, "tags": ["electronics", "accessories"]},
{"sku": "C789", "name": "Mouse", "price": 25, "tags": ["electronics", "accessories"]}
],
"categories": ["electronics", "books", "clothing"]
}
// Sample 3: Nested Configuration
{
"app": {
"name": "My App",
"version": "1.0.0",
"settings": {
"darkMode": true,
"fontSize": 14,
"plugins": {
"auth": {"enabled": true, "type": "jwt"},
"logger": {"enabled": false}
}
}
}
}
// Sample 4: Array of Simple Values
[10, 20, 30, 40, 50]
// Sample 5: Mixed Data Types
{
"stringVal": "hello",
"numberVal": 123.45,
"booleanVal": false,
"nullVal": null,
"arrayVal": [1, "two", true],
"objectVal": {"a": 1}
}
// Sample 6: Deeply Nested Structure
{
"level1": {
"level2": {
"level3": {
"data": "deep value"
}
}
}
}
```
DEPLOYMENT NOTES:
- **Build Tool**: Vite or Create React App (CRA) with necessary configurations for React and Tailwind CSS.
- **Environment Variables**: Use `.env` files for configuration (e.g., `VITE_API_BASE_URL` if future API integrations are planned). Ensure sensitive keys are never client-side.
- **Performance Optimizations**:
* Code Splitting: Use React's `lazy` and `Suspense` for different sections of the app if it grows complex.
* Memoization: Use `React.memo`, `useMemo`, `useCallback` judiciously to prevent unnecessary re-renders.
* Tree Shaking: Ensure the build tool effectively removes unused code.
* Debouncing: Implement debouncing for the query input to avoid excessive processing on every keystroke.
* Web Workers: For heavy JSON parsing or query computation, consider offloading the work to a Web Worker to keep the main UI thread responsive.
- **Hosting**: Static site hosting platforms like Vercel, Netlify, GitHub Pages are suitable for a SPA. Ensure adequate build time and serverless function limits if using serverless backends for any features.
- **HTTPS**: Always serve the application over HTTPS.