자바스크립트에서 JSON 데이터를 이용하여 테이블 생성하기

자바스크립트를 사용하여 JSON 데이터를 테이블로 만들 수 있습니다. JSON 데이터는 자바스크립트 객체로 쉽게 변환되므로, 이를 이용하여 테이블을 생성할 수 있습니다.

JSON 데이터 가져오기

먼저, JSON 데이터를 가져와야 합니다. 이를 위해서는 fetch 메소드나 XMLHttpRequest 객체를 사용하여 서버에서 데이터를 가져올 수 있습니다. 예를 들어, 아래와 같이 서버로부터 JSON 데이터를 가져오는 함수를 작성할 수 있습니다.

async function getJSONData(url) {
  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}

테이블 생성하기

JSON 데이터를 가져왔다면, 이를 테이블로 변환해주어야 합니다. 이를 위해서는 자바스크립트를 사용하여 DOM 요소를 생성하고 데이터를 채워넣어야 합니다.

function createTable(data) {
  const table = document.createElement('table');

  // 헤더 생성
  const thead = document.createElement('thead');
  const headers = Object.keys(data[0]);
  const headerRow = document.createElement('tr');
  headers.forEach((header) => {
    const th = document.createElement('th');
    th.textContent = header;
    headerRow.appendChild(th);
  });
  thead.appendChild(headerRow);
  table.appendChild(thead);

  // 내용 생성
  const tbody = document.createElement('tbody');
  data.forEach((rowData) => {
    const row = document.createElement('tr');
    headers.forEach((header) => {
      const cell = document.createElement('td');
      cell.textContent = rowData[header];
      row.appendChild(cell);
    });
    tbody.appendChild(row);
  });
  table.appendChild(tbody);

  return table;
}

테이블 출력하기

마지막으로, 생성한 테이블을 웹 페이지에 출력해야 합니다. 예를 들어, 아래와 같이 특정 요소에 테이블을 추가하는 함수를 작성할 수 있습니다.

function appendTableToElement(element, data) {
  const table = createTable(data);
  element.appendChild(table);
}

이제 가져온 JSON 데이터를 사용하여 테이블을 생성하고 출력할 수 있습니다.

const jsonData = await getJSONData('https://example.com/api/data');
const container = document.getElementById('tableContainer');
appendTableToElement(container, jsonData);

위 예제에서는 https://example.com/api/data 주소에서 JSON 데이터를 가져와서 tableContainer ID를 가진 요소에 테이블을 추가합니다.

#javascript #JSON #테이블생성