본문 바로가기
GAS/[Js_손코딩]

[Js] Google Sheets JSON data for web pages Sheet Data with Headings 리뷰

by 일등미노왕국 2024. 5. 5.

https://www.youtube.com/watch?v=3QWzYqZd0w4&t=282s&ab_channel=LaurenceSvekis

 

스프레드시트의 내용을 웹상에 Table 형태로 출력하는 코드에 대해서 리뷰해보겠다.

 

본인이 최근 건강이 안좋아져서 당관리를 하고 있다. 그래서 혈당을 기록하고 있는 상태인데, 이번 코드를 적용해 보기로 하였다.

 

Html 코드이다.

더보기
<!DOCTYPE html>
<html></html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Share your Google Sheets</title>
    <style>
        .box {
            display: inline-block;
            width: 33%;
            text-align: center;
        }
        .heading {
            font-size: 1.2em;
            color: white;
            background-color: black;
            padding: 0.3em;
        }
        .row {
            padding: 0.3em;
        }

        .output {
            padding-top: 2em;
        }
    </style>
</head>
<body>
    <h1>혈당체크</h1>
    <div>
        <p>혈당체크를 기록하여 다시 건강한 몸으로..
            <br>2004.05
        </p>
        <button>혈당확인</button>
        <div class="output"></div>

        <script src="apps2.js"></script>
    
</body>
        
</html>

JavaScript 코드이다.

더보기
const output = document.querySelector('.output');
const btn = document.querySelector('button');
const url = 'https://docs.google.com/spreadsheets/d/'
const ssid = '1jv0Y6-h7oHk5m17_d-uZYdZAMJ0rOYYP4W0QJGCVJMk'

const query1 = '/gviz/tq?';
const query2 = 'tqx=out:json';

btn.addEventListener('click', getData);

function getData(){
    const endpoint1 = `${url}${ssid}${query1}&${query2}`
    fetch(endpoint1)
        .then(res => res.text())
        .then(data => {
            const temp = data.substr(47).slice(0,-2);
            const json = JSON.parse(temp);
            const headings = makeCell(output, '', 'heading');

            console.log(json);
            json.table.cols.forEach((col) => {
                const el = makeCell(headings, col.label, 'box');
            })
            json.table.rows.forEach((row)=>{
                const div = makeCell(output,'','row');
                row.c.forEach((cell)=>{
                    const ele1 = makeCell(div, `${cell.v}`, 'box');
                })

            })
               
        })
            
            function makeCell(parent, html, classAdd){
                const ele = document.createElement('div');
                parent.append(ele);
                ele.innerHTML = html
                ele.classList.add(classAdd);
                return ele;

            }
            

}

 

코드를 단계별로 설명해보면...

 

1.  function getData() { ... }: getData 함수는 데이터를 가져오고 가공하여 표 형식으로 출력하는 작업을 담당을 한다.

 

2.  const endpoint1 = ${url}${ssid}${query1}&${query2}``: 가져올 데이터의 엔드포인트 URL을 생성을 한다. 이렇게 하지않고 바로 url로 fetch로 가져오게 되면 공유에러가 발생하기 때문에 google.visualization.Query.setResponse 작업을 거쳐야 한다. 이렇게 하면 스트레트시트는 DB가 되고 쿼리문을 통해 원하는 데이터를 가져올 수 있다.

 

3. fetch(endpoint1) .then(res => res.text()) .then(data => { ... }): fetch 함수를 사용하여 엔드포인트에서 데이터를 가져와서, 연속적으로 then 메서드를 사용하여 응답을 텍스트로 변환하고 데이터를 처리한다.

 

4. const temp = data.substr(47).slice(0,-2);: 가져온 데이터에서 필요한 부분만 추출하여 가공한다.

fetch 로 받아온 데이터를 텍스트화 시키면 위와 같이 값들이 출력하게 되는데 data중에서 47번째 인덱스부터 끝에서 2번째 글자까지를 슬라이싱 하라는 의미이다. 

/*O_o*/
google.visualization.Query.setResponse({내용})

이렇게 하면 내용만 추출된다.

 

5. const json = JSON.parse(temp);: 가공한 데이터를 JSON 형식으로 파싱한다.

 

6. function makeCell(parent, html, classAdd) { ... }: 셀(또는 헤딩)을 만드는 함수이다. 이 함수는 부모 요소에 새로운 <div>를 추가하고, 내용과 클래스를 설정한 후 생성된 요소를 반환하는 역활을 한다...가장 핵심 함수이다.

 

 

7. const headings = makeCell(output, '', 'heading'); console.log(headings);: 표의 헤딩(제목)을 만들기 위해 makeCell 함수를 호출한다. 새로운 <div> 요소를 생성하여 지정된 클래스를 추가하고, 부모 요소에 추가한다.

 

8. 열과 행을 반복하며 각 테그에 데이터를 추가한다.

 

 

이코드를 이해하려면 /gviz/tq?  구글비주얼화로 가져온 데이터의 구조를 확인하여야 하는데, 

가져온 Object에서 table을 열어보면 

cols값에 label값은 헤더값이고, rows 각 행은 c 이고 v 또는 f 값이 Value값이다. 이 구조를 확인하면 각 열과 행을 반복하면서 왜 매소드에 c또는 v가 사용되었는지 알 수 있을 것이다.

 

 

슬프다....ㅜ.,ㅡ

댓글