json2jsx
v1.3.2
Published
A node js library that transforms a json file into a set of react components
Readme
Json2jsx
A Node.js library (requires Node 18+) that turns a JSON view model into a tree of React components. It reads structure from your JSON, fills JSX templates, formats with Prettier, and writes files under output/.
Features
- Nested objects → child components
- Arrays of objects → one component per item (
.map()in the parent) - Arrays of primitives → comma-separated text with a label
- Image-like fields (
thumbnailUrl,heroImage,avatar, …) →<img>plus caption - Scalar fields → labeled text (
Title: …,Summary: …) - Booleans → read-only checkbox
- URL fields (non-image) →
<a href="…">link - Functional (default) or statefull (class) templates via
config.json
Quick start (browser preview)
One command — generate components, install the playground if needed, and open the dev server:
yarn preview # test.json → http://localhost:5173
yarn preview:gallery # media-gallery sample
yarn preview:pokemon # pokemon (PokéAPI) sampleCustom JSON and output prefix:
yarn preview -- json_samples/pokemon.json pokemonGenerate and scaffold only (no dev server):
yarn preview -- --setup-onlyyarn start is an alias for yarn preview (default test.json).
Manual steps (optional)
yarn demo:gallery
yarn playground:install # once
yarn playground # http://localhost:5173The playground picks the matching json_samples/<name>.json from the generated folder name (<prefix>_<basename>, e.g. gallery_media-gallery → media-gallery.json).
Preview another generated folder
After json2jsx json_samples/test.json test_run (or yarn demo), run:
yarn playgroundThe playground picks output/test_run_test/ by default, or the newest folder under output/ that contains App.js.
For a specific folder (timestamp or custom prefix):
# Clear a wrong folder name from an earlier session
Remove-Item Env:VITE_OUTPUT_DIR -ErrorAction SilentlyContinue
yarn playground -- test_run_test
# or
node scripts/run-playground.js 20260531143000_testThe playground template is copied from scripts/playground/ into gitignored output/playground/.
Scripts
| Script | Description |
|--------|-------------|
| yarn preview | Generate + playground install + Vite dev server (default test.json) |
| yarn preview:gallery | Same for media-gallery.json |
| yarn preview:pokemon | Same for pokemon.json |
| yarn preview -- <file.json> [prefix] | Custom input; add --setup-only to skip the dev server |
| yarn start | Alias for yarn preview |
| yarn demo | Generate only → output/test_run_test/ |
| yarn demo:gallery | Generate only → output/gallery_media-gallery/ |
| yarn demo:pokemon | Generate only → output/pokemon_pokemon/ |
| yarn generate -- <file.json> [prefix] | Custom input (via node cli.js) |
| yarn playground:setup | Copy playground template only |
| yarn playground:install | Setup + yarn install in output/playground/ |
| yarn playground | Sync template and start Vite (existing output) |
| yarn test | Jest suite |
Command line
json2jsx path/to/data.json
json2jsx path/to/data.json my_prefixWith defaultFolderPrefix: "currentdate" in config.json, output folders look like output/20260531143000_data/.
Typical layout:
output/<prefix>_<basename>/
App.js
App.css
ComponentA/
ComponentA.jsx
SubComponentB/
SubComponentB.jsx- Root component:
App.js(name fromdefaultRootComponentName) - Nested components:
.jsxunder subfolders
Media gallery sample
json_samples/media-gallery.json uses Glauco Pater’s Unsplash photos and demonstrates:
- Page metadata (title, summary, tags, hero image)
- Nested
author→contact gallery.items[]with thumbnails and metadatahighlights[]andrelatedLinks[]as lists
yarn demo:galleryGenerated parents render lists roughly like:
{props.highlights?.map((item, index) => (
<Highlights key={index} {...item} />
))}Scalar fields are labeled in the JSX, for example:
<span className="Title">
<strong>Title:</strong> {props.title}
</span>Using output in your own React app
- Generate components (see above).
- Import the root
App.jsand pass the same JSON shape as props:
import App from "./output/gallery_media-gallery/App.js";
import data from "./json_samples/media-gallery.json";
<App {...data} />;- Or wire only the subtree you need, matching the generated prop names (
page,author, etc.).
For Create React App, CodeSandbox, or similar, point the entry file at the generated root and pass your JSON file as props (see tutorial images below).


How generation works
JSON file → manageData (props vs children) → JSX templates → Prettier → output/- Objects → child component + import
- Arrays of objects → child component; parent uses
.map()to render each item - Arrays of primitives → single labeled span with
.join(", ") - null → empty string prop
- Image-like keys →
<figure>with<img>and<figcaption>
Generated CSS outlines the component tree (borders/boxes) so structure is visible before you style for production.
Configuration
| Option | Default | Description |
|--------|---------|-------------|
| outputDir | ./output | Output directory |
| templatesFolder | ./src/react-templates | functional / statefull templates |
| silentMode | false | Log each created file when false |
| defaultComponentType | functional | functional or statefull |
| defaultRootComponentName | App | Root file base name |
| defaultFolderPrefix | currentdate | Folder prefix; currentdate = timestamp |
| cleanUpTestOutput | true | Delete test output after yarn test |
Programmatic API
getRootComponent is async (Prettier 3):
const json2jsx = require("json2jsx");
await json2jsx.getRootComponent("App", "./data.json", "my_prefix");Sync helpers include manageData, getProp, getComponentTag, and getDataFromFile.
Caveats
- Input must use a
.jsonextension. - Component shape for arrays is inferred from the first element only; you may need to hand-edit templates for heterogeneous lists.
- Config key
statefullis the legacy spelling for class-based templates. - Image fields use a name heuristic; rename keys or edit generated JSX for full control.
- Playground and
output/are local dev aids; onlyindex.js,cli.js,config.json, andsrc/ship on npm (package.jsonfiles).
Samples in this repo
| File | Purpose |
|------|---------|
| json_samples/test.json | Small tree (yarn demo) |
| json_samples/media-gallery.json | Nested objects, lists, images (yarn demo:gallery) |
| json_samples/nasa.open.api.json | Large real-world API payload |
| json_samples/pokemon.json, anapioficeandfire.json, … | More fixtures |
When installed from npm, samples also appear under node_modules/json2jsx/json_samples/.
External APIs used by sample JSON
More lists: easy APIs without auth, public-apis.
Development
yarn install
yarn testCI runs tests on Node 18, 20, and 22 (see .github/workflows/ci.yml).
Background
React apps often mirror a JSON (or JSON-like) view model. The mapping is rarely one-to-one, but nested objects and arrays frequently match components and lists. Json2jsx bootstraps that folder structure so you can refine markup and styling afterward.
Thanks
Andrea Falzetti for the template-literal approach that avoids eval / new Function.
