json-to-html-table-with-lit
Learn how to create a dynamic HTML table from JSON data using a Lit web component, with examples for fetching data from a URL or using inline JSON, and the ability to make the table editable.
What this skill does
# JSON to HTML Table with Lit
In this article I will go over how to set up a [Lit](https://lit.dev/) web component and use it to create a HTML [Table](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) from json url or inline json.
> **TLDR** The final source [here](https://github.com/rodydavis/lit-html-table) and an online [demo](https://rodydavis.github.io/lit-html-table/).
## Prerequisites
* Vscode
* Node >= 16
* Typescript
## Getting Started
We can start off by navigating in terminal to the location of the project and run the following:
```
npm init @vitejs/app --template lit-ts
```
Then enter a project name `lit-html-table` and now open the project in vscode and install the dependencies:
```
cd lit-html-table
npm i lit
npm i -D @types/node
code .
```
Update the `vite.config.ts` with the following:
```
import { defineConfig } from "vite";
import { resolve } from "path";
export default defineConfig({
base: "/lit-html-table/",
build: {
lib: {
entry: "src/lit-html-table.ts",
formats: ["es"],
},
rollupOptions: {
input: {
main: resolve(__dirname, "index.html"),
},
},
},
});
```
## Template
Open up the `index.html` and update it with the following:
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JSON to Lit HTML Table</title>
<script type="module" src="/src/lit-html-table.ts"></script>
</head>
<body>
<lit-html-table src="https://jsonplaceholder.typicode.com/posts">
<!-- <span slot="title" style="color: red;">Title</span> -->
<!-- <script type="application/json">
[
{
"id": "0",
"name": "First Item"
}
]
</script> -->
</lit-html-table>
</body>
</html>
```
We are passing a src attribute to the web component for this example but we can also add a script tag with the type attribute set to `application/json` with the contents containing the json.
If any table header cell needed to be replaced an element can be provided with the slot name set to the key in the json object.
## Web Component
Before we update our component we need to rename `my-element.ts` to `lit-html-table.ts`
Open up `lit-html-table.ts` and update it with the following:
```
import { html, css, LitElement } from "lit";
import { customElement, property } from "lit/decorators.js";
type ObjectData = { [key: string]: any };
@customElement("lit-html-table")
export class LitHtmlTable extends LitElement {
@property() src = "";
data?: ObjectData[];
static styles = css`
tr {
text-align: var(--table-tr-text-align, left);
vertical-align: var(--table-tr-vertical-align, top);
padding: var(--table-tr-padding, 10px);
}
`;
render() {
// Check if data is loaded
if (!this.values) {
return html`<slot name="loading">Loading...</slot>`;
}
// Check if items are not empty
if (this.values.length === 0) {
return html`<slot name="empty">No Items Found!</slot>`;
}
// Convert JSON to HTML Table
return html`
<table>
<thead>
<tr>
${Object.keys(this.values[0]).map((key) => {
const name = key.replace(/\b([a-z])/g, (_, val) =>
val.toUpperCase()
);
return html`<th>
<slot name="${key}">${name}</slot>
</th>`;
})}
</tr>
</thead>
<tbody>
${this.values.map((item) => {
return html`
<tr>
${Object.values(item).map((row) => {
return html`<td>${row}</td>`;
})}
</tr>
`;
})}
</tbody>
</table>
`;
}
async firstUpdated() {
await this.fetchData();
}
// Download the latest json and update it locally
async fetchData() {
let _data: any;
if (this.src.length > 0) {
// If a src attribute is set prefer it over any slots
_data = await fetch(this.src).then((res) => res.json());
} else {
// If no src attribute is set then grab the inline json in the slot
const elem = this.parentElement?.querySelector(
'script[type="application/json"]'
) as HTMLScriptElement;
if (elem) _data = JSON.parse(elem.innerHTML);
}
this.values = this.transform(_data ?? []);
this.requestUpdate();
}
transform(data: any) {
return data;
}
}
```
We have defined a few [CSS Custom Properties](https://developer.mozilla.org/en-US/docs/Web/CSS/--*) to style the table cell but many more can be added here.
If everything goes well run the command `npm run dev` and the follow should appear:

## Editing
What if we wanted to support editing of any cell? With Lit and Web Components we can progressively enhance the experience without changing the html.
At the top of the class add the following boolean property:
```
@property({ type: Boolean }) editable = false;
```
Now update the `tbody` tag in the render method:
```
<tbody>
${this.values.map((item, index) => {
return html`
<tr>
${Object.entries(item).map((row) => {
return html`<td>
${this.editable
? html`<input
value="${row[1]}"
type="text"
@input=${(e: any) => {
const value = e.target.value;
const key = row[0];
const current = this.values![index];
current[key] = value;
this.values![index] = current;
this.requestUpdate();
this.dispatchEvent(
new CustomEvent("input-cell", {
detail: {
index: index,
data: current,
},
})
);
}}
/>`
: html`${row[1]}`}
</td>`;
})}
</tr>
`;
})}
</tbody>
```
By checking to see if the `editable` and if `true` return an input with an event listener to update the data and dispatch an `input` event.
Add the `editable` attribute to the `index.html`:
```
<lit-html-table editable> ... </lit-html-table>
```
After a reload the table should look like this and any cell can be edited.

An event listener can be added just before the closing `body` tag in `index.html` to grab the latest values or cell information:
```
<script>
const elem = document.querySelector("lit-html-table");
elem.addEventListener(
"input-cell",
(e) => {
// Index and data for the individual cell
const { index, data } = e.detail;
// New array of json items
const values = elem.values;
},
false
);
</script>
```
This can be taken farther by checking for the type of the value and returning a color, number or checkbox input.
## Conclusion
If you want to learn more about building with Lit you can read the docs [here](https://lit.dev/). There is also an example on the Lit playground [here](https://lit.dev/playground/#project=W3sibmFtZSI6ImxpdC1odG1sLXRhYmxlLnRzIiwiY29udGVudCI6ImltcG9ydCB7IGh0bWwsIGNzcywgTGl0RWxlbWVudCB9IGZyb20gXCJsaXRcIjtcbmltcG9ydCB7IGN1c3RvbUVsZW1lbnQsIHByb3BlcnR5IH0gZnJvbSBcImxpdC9kZWNvcmF0b3JzLmpzXCI7XG5cbnR5cGUgT2JqZWN0RGF0YSA9IHsgW2tleTogc3RyaW5nXTogYW55IH07XG5cbkBjdXN0b21FbGVtZW50KFwibGl0LWh0bWwtdGFibGVcIilcbmV4cG9ydCBjbGFzcyBMaXRIdG1sVGFibGUgZXh0ZW5kcyBMaXRFbGVtZW50IHtcbiAgQHByb3BlcnR5KCkgc3JjID0gXCJcIjtcblxuICBkYXRhPzogT2JqZWN0RGF0YVtdO1xuXG4gIHN0YXRpYyBzdHlsZXMgPSBjc3Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.