본문으로 건너뛰기Skip to content
예제 첫화면Examples home

JSON 데이터로 표 만들기Build a table from JSON

서버에서 받은 데이터(JSON)를 읽어 그대로 표에 넣어요. 행 수를 100개에서 2만 개까지 바꿔 보고, 지역·상품별로 묶어서 볼 수도 있어요.Read a JSON response with JSON.parse and pass it straight to rows. Try 100 up to 20,000 rows, and group by city or product.

입문Beginner
직접 써 보기Live previewJSON 데이터로 표 만들기Build a table from JSON

코드Code

탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.

이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)

빌드 도구(Vite 등)를 쓰는 프로젝트용 모듈 파일이에요. 설치 없이 바로 돌려 보려면 HTML 탭이나 직접 해보기를 쓰세요.

버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="행 수" id="count">
      <option value="0">0행 (빈 표)</option>
      <option value="10">10행</option>
      <option value="100" selected>100행</option>
      <option value="1000">1,000행</option>
      <option value="10000">10,000행</option>
      <option value="20000">20,000행</option>
    </select>
    <select aria-label="묶어 보기" id="groupBy">
      <option value="none">묶지 않기</option>
      <option value="city">지역별</option>
      <option value="product">상품별</option>
      <option value="customer">고객별</option>
    </select>
    <button type="button" id="showJson">데이터 모양 보기</button>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('count').addEventListener('change', (event) => actions.count(api, event.target.value));
document.getElementById('groupBy').addEventListener('change', (event) => actions.groupBy(api, event.target.value));
document.getElementById('showJson').addEventListener('click', () => actions.showJson(api));
example.js
// 서버가 돌려준 JSON 문자열을 가정해요. 실제로는 fetch(...).then((res) => res.json())으로 받는 값이에요.
// 여기서는 같은 모양의 JSON 문자열을 직접 만들어서, JSON.parse로 읽어 그리드에 넣어요.
const customers = ['김서연', '이준호', '박민지', '최도윤', '정하은', '강지후', '윤서아', '임태민'];
const cities = ['서울', '부산', '대구', '인천', '광주', '대전', '울산', '제주'];
const products = [
  '무선 이어폰',
  '노트북 14형',
  '스마트워치',
  '태블릿 11형',
  '보조배터리',
  '블루투스 스피커',
];
const colors = ['블랙', '화이트', '실버', '네이비', '핑크'];
function makeJson(count) {
  const list = Array.from({ length: count }, (_, i) => ({
    id: `C${String(i + 1).padStart(5, '0')}`,
    customer: customers[(i * 7) % customers.length],
    city: cities[(i * 5 + (i >> 2)) % cities.length],
    product: products[(i * 3 + (i >> 1)) % products.length],
    color: colors[(i * 11) % colors.length],
    price: 19000 + ((i * 7919) % 90) * 10000,
    quantity: 1 + ((i * 13) % 12),
  }));
  return JSON.stringify(list);
}
let jsonText = makeJson(100);
let log = () => { };
export const options = {
  columns: [
    { id: 'id', title: '주문번호', width: 110 },
    { id: 'customer', title: '고객', width: 100, groupable: true },
    { id: 'city', title: '지역', width: 90, groupable: true },
    { id: 'product', title: '상품', width: 160, groupable: true },
    { id: 'color', title: '색상', width: 90 },
    {
      id: 'price',
      title: '단가',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (v) => `${Number(v).toLocaleString('ko-KR')}원`,
    },
    { id: 'quantity', title: '수량', kind: 'number', width: 80, align: 'end' },
  ],
  // JSON.parse의 결과는 배열이에요. 그대로 rows에 넣으면 돼요.
  rows: JSON.parse(jsonText),
  rowKey: 'id',
  showRowNumbers: true,
};
export function setup(_api, write) {
  log = write;
  write({
    ko: '데이터는 JSON.parse로 읽은 배열이에요. "JSON 모양 보기"를 눌러 보세요.',
    en: 'The data is an array read with JSON.parse. Press "Show JSON shape".',
  });
}
export const actions = {
  // 행 수를 바꿔 다시 읽어요. 많은 행도 스크롤은 화면에 보이는 줄만 그려서 가벼워요.
  count: (api, value) => {
    const count = Number(value ?? 100);
    jsonText = makeJson(count);
    api.setRows(JSON.parse(jsonText));
    log({
      ko: `${count.toLocaleString('ko-KR')}행을 읽었어요. JSON 글자 수는 ${jsonText.length.toLocaleString('ko-KR')}자예요.`,
      en: `Read ${count.toLocaleString('en-US')} rows. The JSON is ${jsonText.length.toLocaleString('en-US')} characters long.`,
    });
  },
  showJson: () => {
    const sample = JSON.parse(jsonText).slice(0, 2);
    log({
      ko: `JSON 모양 (앞 2행)\n${JSON.stringify(sample, null, 2)}`,
      en: `JSON shape (first 2 rows)\n${JSON.stringify(sample, null, 2)}`,
    });
  },
  groupBy: (api, value) => api.setGroupBy(value && value !== 'none' ? [value] : []),
};

Module files for a project with a bundler such as Vite. To run it with no setup, use the HTML tab or Try it.

When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.

index.html
<div id="app">
  <div class="toolbar">
    <select aria-label="Rows" id="count">
      <option value="0">0 rows (empty)</option>
      <option value="10">10 rows</option>
      <option value="100" selected>100 rows</option>
      <option value="1000">1,000 rows</option>
      <option value="10000">10,000 rows</option>
      <option value="20000">20,000 rows</option>
    </select>
    <select aria-label="Group by" id="groupBy">
      <option value="none">No grouping</option>
      <option value="city">By city</option>
      <option value="product">By product</option>
      <option value="customer">By customer</option>
    </select>
    <button type="button" id="showJson">Show JSON</button>
  </div>
  <div id="grid" style="height: 360px"></div>
</div>
<script type="module" src="./main.js"></script>
main.js
import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('count').addEventListener('change', (event) => actions.count(api, event.target.value));
document.getElementById('groupBy').addEventListener('change', (event) => actions.groupBy(api, event.target.value));
document.getElementById('showJson').addEventListener('click', () => actions.showJson(api));
example.js
// Assume this is the JSON string a server returned. In practice you would get it with fetch(...).then((res) => res.json()).
// Here we build a JSON string of the same shape ourselves, read it with JSON.parse and feed it to the grid.
const customers = [
  'Liam Carter',
  'Emma Stone',
  'Noah Brooks',
  'Olivia Reed',
  'Ethan Hayes',
  'Ava Morgan',
  'Mason Clark',
  'Sophia Bell',
];
const cities = ['Seoul', 'Busan', 'Daegu', 'Incheon', 'Gwangju', 'Daejeon', 'Ulsan', 'Jeju'];
const products = [
  'Wireless Earbuds',
  'Laptop 14"',
  'Smartwatch',
  'Tablet 11"',
  'Power Bank',
  'Bluetooth Speaker',
];
const colors = ['Black', 'White', 'Silver', 'Navy', 'Pink'];
function makeJson(count) {
  const list = Array.from({ length: count }, (_, i) => ({
    id: `C${String(i + 1).padStart(5, '0')}`,
    customer: customers[(i * 7) % customers.length],
    city: cities[(i * 5 + (i >> 2)) % cities.length],
    product: products[(i * 3 + (i >> 1)) % products.length],
    color: colors[(i * 11) % colors.length],
    price: 19 + ((i * 7919) % 90) * 10,
    quantity: 1 + ((i * 13) % 12),
  }));
  return JSON.stringify(list);
}
let jsonText = makeJson(100);
let log = () => { };
export const options = {
  columns: [
    { id: 'id', title: 'Order No.', width: 110 },
    { id: 'customer', title: 'Customer', width: 120, groupable: true },
    { id: 'city', title: 'City', width: 90, groupable: true },
    { id: 'product', title: 'Product', width: 160, groupable: true },
    { id: 'color', title: 'Color', width: 90 },
    {
      id: 'price',
      title: 'Unit price',
      kind: 'number',
      width: 120,
      align: 'end',
      formatValue: (v) => `$${Number(v).toLocaleString('en-US')}`,
    },
    { id: 'quantity', title: 'Qty', kind: 'number', width: 80, align: 'end' },
  ],
  // The result of JSON.parse is an array. Put it straight into rows.
  rows: JSON.parse(jsonText),
  rowKey: 'id',
  showRowNumbers: true,
};
export function setup(_api, write) {
  log = write;
  write('The data is an array read with JSON.parse. Press "Show JSON shape".');
}
export const actions = {
  // Change the row count and read again. Even with many rows, scrolling stays light because only the visible lines are drawn.
  count: (api, value) => {
    const count = Number(value ?? 100);
    jsonText = makeJson(count);
    api.setRows(JSON.parse(jsonText));
    log(`Read ${count.toLocaleString('en-US')} rows. The JSON is ${jsonText.length.toLocaleString('en-US')} characters long.`);
  },
  showJson: () => {
    const sample = JSON.parse(jsonText).slice(0, 2);
    log(`JSON shape (first 2 rows)\n${JSON.stringify(sample, null, 2)}`);
  },
  groupBy: (api, value) => api.setGroupBy(value && value !== 'none' ? [value] : []),
};