본문 바로가기
FrontEnd/JavaScript

내가 JSON Viewer를 짠 방식

by 위그든씨 2023. 11. 4.

data 예시

이러한 객체로 이루어진 배열 data 가 있을 때, 이것의 JSON형태로 볼 수 있는 Viewer를 웹에 띄울려고 했다.

뷰어는 데이터를 직접적으로 편집 가능 할 수 있게 하는 것이 목표.

 

목표 사진

뷰어는 데이터의 편집까지 가능하므로 곧 에디터 역할을 함.

두가가지 방식을 생각해봄.

위의 객체를 items 라고 명명했을 때,

1. 아래와 같이 pre 태그 안에 input 박스를 넣어서 key값에 대한 value만 조작 가능하게 만들기

this.$primeEditor.innerHTML = `
        <pre>
        
    [
        ${this.state.items
            .map(
                (node, idx) => `
            {
                "id": <input class="EditInput id" data-id=${idx} value=${node.id} type="number" />
                "value": <input class="EditInput value" data-id=${idx} value=${node.value} type="number" />
            },
        `
            )
            .join('')}
    ]
        </pre>
        `;
        
// 이것은 json 편집기라기엔 의미가 없다 생각해서 폐기

 

2. 두 번째 방식은 textarea 안에 JSON.stringfy(items)를 넣어준 뒤, 이 후 컨펌을 받을 때 try catch를 통해

변경 된 데이터에 대해

1) JSON 형태를 유지하는지

2) key값 변화는 없는지

3) key- id 의 중복 된 값은 없는지 를 체크함

this.$primeEditor.innerHTML = `
    <textarea id="editorTextArea" cols="91" rows=${this.state.items.length * 6}>
		${JSON.stringify(this.state.items, null, 4)}
    </textarea>
    `;
    };
this.$target.addEventListener('click', (e) => {
        const button = e.target.closest('.ApplyButton');
        if (!button) return;

        const $editorTextArea = document.querySelector('#editorTextArea');
        try {
            const newItems = JSON.parse($editorTextArea.value);

            if (!isValidate(newItems)) {
                return;
            }
            handleApply(newItems);
        } catch (error) {
            window.alert('json 형태를 유지해주세요.');
        }
    });

결과