← 블로그로 돌아가기

JSON Beautifier 가이드: 데이터를 읽기 쉽게 만들기

JSON beautifier를 사용하여 압축된 JSON을 읽기 쉬운 형식으로 변환하는 방법을 배우세요. 도구, 기술 및 모범 사례에 대한 완벽한 가이드입니다.

Big JSON Team10분 소요tutorial
B

Big JSON Team

Technical Writer

Expert in JSON data manipulation, API development, and web technologies. Passionate about creating tools that make developers' lives easier.

10 분 읽기

# JSON Beautifier 가이드: 데이터를 읽기 쉽게 만들기

JSON beautification(또는 pretty printing)은 압축된 JSON을 사람이 읽을 수 있는 형식으로 변환하는 프로세스입니다. 이 가이드는 JSON beautifier를 사용하는 모든 방법, 도구 및 모범 사례를 다룹니다.

JSON Beautifier란?

JSON beautifier는 압축된(최소화된) JSON 데이터를 가져와 적절한 들여쓰기, 줄바꿈 및 간격을 추가하여 읽고 이해하기 쉽게 만드는 도구입니다.

압축된 JSON

{"user":{"id":1,"name":"홍길동","email":"hong@example.com","address":{"city":"서울","zipCode":"12345"},"skills":["JavaScript","Python","Go"]}}

Beautified JSON

{

"user": {

"id": 1,

"name": "홍길동",

"email": "hong@example.com",

"address": {

"city": "서울",

"zipCode": "12345"

},

"skills": [

"JavaScript",

"Python",

"Go"

]

}

}

Beautification이 중요한 이유

1. 가독성 향상

구조화된 JSON은 스캔하고 이해하기 훨씬 쉽습니다.

2. 쉬운 디버깅

오류, 누락된 쉼표 및 구조 문제를 빠르게 발견합니다.

3. 더 나은 협업

팀원들이 JSON 데이터를 이해하고 검토할 수 있습니다.

4. 문서화

beautified JSON은 문서에서 더 잘 표시됩니다.

5. 학습

초보자가 JSON 구조를 이해하는 데 도움이 됩니다.

온라인 JSON Beautifier

1. JSON Beautifier (jsonbeautifier.org)

기능:
  • 즉시 beautification
  • 구문 강조
  • 오류 감지
  • 다운로드 옵션

사용 방법:
  • 압축된 JSON 붙여넣기
  • "Beautify" 클릭
  • 포맷된 결과 복사
  • 2. JSON Formatter (jsonformatter.org)

    특징:
    • 실시간 미리보기
    • 들여쓰기 옵션 (2, 4, 탭)
    • 다크 모드
    • 공유 가능한 링크

    3. Code Beautify

    URL: codebeautify.org/jsonviewer 고급 기능:
    • 트리 뷰
    • 검증
    • 압축/beautify 토글
    • 파일 업로드

    브라우저 도구

    Chrome/Edge DevTools

    방법 1: Console 사용
    // 압축된 JSON 문자열
    

    const compressed = '{"name":"홍길동","age":30}';

    // Beautify

    console.log(JSON.stringify(JSON.parse(compressed), null, 2));

    방법 2: Network 탭
  • Network 탭 열기
  • API 응답 클릭
  • "Preview" 또는 "Response" 탭 선택
  • 자동으로 beautified 표시
  • Firefox

    JSON Viewer 내장:
    • JSON 응답 자동 포맷팅
    • 접을 수 있는 섹션
    • 검색 기능
    • 원본/포맷 토글

    코드 에디터

    Visual Studio Code

    내장 Beautifier: 방법 1: 명령 팔레트
  • Ctrl + Shift + P
  • "Format Document" 입력
  • Enter
  • 방법 2: 키보드 단축키
    • Windows/Linux: Shift + Alt + F
    • macOS: Shift + Option + F

    자동 포맷팅:
    {
    

    "editor.formatOnSave": true,

    "editor.formatOnPaste": true,

    "[json]": {

    "editor.defaultFormatter": "vscode.json-language-features"

    }

    }

    Sublime Text

    패키지: Pretty JSON 설치:
  • Package Control 열기
  • "Install Package" 선택
  • "Pretty JSON" 검색
  • 설치
  • 사용:
    • Ctrl + Alt + J (Windows/Linux)
    • Cmd + Ctrl + J (macOS)

    Atom

    패키지: atom-beautify 설치:
    apm install atom-beautify
    사용:
    • Ctrl + Alt + B

    명령줄 도구

    jq

    가장 강력한 JSON 프로세서:

    설치:
    # macOS
    

    brew install jq

    # Ubuntu/Debian

    sudo apt-get install jq

    # Windows (Chocolatey)

    choco install jq

    Beautify:
    # 파일에서
    

    jq '.' input.json

    # 표준 입력에서

    echo '{"name":"홍길동","age":30}' | jq '.'

    # 파일로 저장

    jq '.' input.json > output.json

    # 사용자 정의 들여쓰기

    jq --indent 4 '.' input.json

    Python json.tool

    기본 사용:
    # 파일 beautify
    

    python -m json.tool input.json

    # 출력 저장

    python -m json.tool input.json output.json

    # 파이프 사용

    cat data.json | python -m json.tool

    # 사용자 정의 들여쓰기

    python -m json.tool --indent 4 input.json

    Node.js

    명령줄에서:
    # 한 줄로
    

    node -e "console.log(JSON.stringify(JSON.parse(require('fs').readFileSync('input.json')), null, 2))"

    # 또는 스크립트 생성

    node beautify.js input.json

    beautify.js:
    const fs = require('fs');
    

    const file = process.argv[2];

    const data = JSON.parse(fs.readFileSync(file, 'utf8'));

    console.log(JSON.stringify(data, null, 2));

    프로그래밍 방식 Beautification

    JavaScript/Node.js

    기본 beautification:
    const compressed = '{"name":"홍길동","age":30,"skills":["JS","Python"]}';
    
    

    // 파싱

    const obj = JSON.parse(compressed);

    // Beautify (들여쓰기 2칸)

    const beautified = JSON.stringify(obj, null, 2);

    console.log(beautified);

    결과:
    {
    

    "name": "홍길동",

    "age": 30,

    "skills": [

    "JS",

    "Python"

    ]

    }

    사용자 정의 replacer:
    const data = {
    

    name: "홍길동",

    password: "secret",

    age: 30

    };

    // 민감한 필드 제외

    const beautified = JSON.stringify(data, (key, value) => {

    if (key === 'password') return undefined;

    return value;

    }, 2);

    Python

    기본 beautification:
    import json
    
    

    # 압축된 JSON

    compressed = '{"name":"홍길동","age":30,"skills":["Python","JS"]}'

    # 파싱

    data = json.loads(compressed)

    # Beautify

    beautified = json.dumps(data, indent=2, ensure_ascii=False)

    print(beautified)

    파일로 작업:
    import json
    
    

    # 파일 읽기

    with open('input.json', 'r', encoding='utf-8') as f:

    data = json.load(f)

    # Beautified로 저장

    with open('output.json', 'w', encoding='utf-8') as f:

    json.dump(data, f, indent=2, ensure_ascii=False)

    정렬된 키:
    beautified = json.dumps(
    

    data,

    indent=2,

    sort_keys=True,

    ensure_ascii=False

    )

    PHP

    <?php
    

    $compressed = '{"name":"홍길동","age":30}';

    // 파싱

    $data = json_decode($compressed);

    // Beautify

    $beautified = json_encode(

    $data,

    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE

    );

    echo $beautified;

    ?>

    Java

    Gson 사용:
    import com.google.gson.Gson;
    

    import com.google.gson.GsonBuilder;

    public class JsonBeautifier {

    public static void main(String[] args) {

    String compressed = "{"name":"홍길동","age":30}";

    Gson gson = new GsonBuilder()

    .setPrettyPrinting()

    .create();

    Object obj = gson.fromJson(compressed, Object.class);

    String beautified = gson.toJson(obj);

    System.out.println(beautified);

    }

    }

    들여쓰기 옵션

    2칸 들여쓰기 (권장)

    {
    

    "user": {

    "name": "홍길동"

    }

    }

    장점:
    • 더 컴팩트
    • 웹 표준
    • 깃허브 기본값

    4칸 들여쓰기

    {
    

    "user": {

    "name": "홍길동"

    }

    }

    장점:
    • 더 명확한 중첩
    • 일부 스타일 가이드

    탭 들여쓰기

    {
    

    "user": {

    "name": "홍길동"

    }

    }

    장점:
    • 사용자가 너비 조정 가능
    • 일부 에디터에서 선호

    고급 Beautification

    사용자 정의 포맷팅

    JavaScript:
    function customBeautify(obj, indent = 2) {
    

    const spaces = ' '.repeat(indent);

    function format(data, level = 0) {

    const currentIndent = spaces.repeat(level);

    const nextIndent = spaces.repeat(level + 1);

    if (Array.isArray(data)) {

    if (data.length === 0) return '[]';

    const items = data.map(item =>

    nextIndent + format(item, level + 1)

    );

    return '[

    ' + items.join(',

    ') + '

    ' + currentIndent + ']';

    }

    if (typeof data === 'object' && data !== null) {

    const keys = Object.keys(data);

    if (keys.length === 0) return '{}';

    const items = keys.map(key =>

    nextIndent + '"' + key + '": ' + format(data[key], level + 1)

    );

    return '{

    ' + items.join(',

    ') + '

    ' + currentIndent + '}';

    }

    return JSON.stringify(data);

    }

    return format(obj);

    }

    // 사용

    const data = {name: "홍길동", age: 30, skills: ["JS", "Python"]};

    console.log(customBeautify(data));

    조건부 압축

    작은 배열은 한 줄에, 큰 배열은 여러 줄에:

    function smartBeautify(obj) {
    

    return JSON.stringify(obj, (key, value) => {

    if (Array.isArray(value) && value.length <= 3) {

    return value; // 작은 배열은 한 줄

    }

    return value;

    }, 2);

    }

    const data = {

    colors: ["빨강", "초록", "파랑"], // 한 줄

    skills: ["JS", "Python", "Go", "Rust", "C++"] // 여러 줄

    };

    대용량 JSON 파일

    스트리밍 Beautification

    Node.js:
    const fs = require('fs');
    

    const JSONStream = require('JSONStream');

    const readStream = fs.createReadStream('large.json');

    const writeStream = fs.createWriteStream('beautified.json');

    readStream

    .pipe(JSONStream.parse(''))

    .pipe(JSONStream.stringify('{

    ', ',

    ', '

    }

    '))

    .pipe(writeStream);

    청크 처리

    const fs = require('fs');
    

    const readline = require('readline');

    async function beautifyLarge(input, output) {

    const rl = readline.createInterface({

    input: fs.createReadStream(input),

    output: fs.createWriteStream(output)

    });

    for await (const line of rl) {

    const parsed = JSON.parse(line);

    const beautified = JSON.stringify(parsed, null, 2);

    console.log(beautified);

    }

    }

    Beautification 모범 사례

    1. 일관된 들여쓰기

    팀 전체에서 동일한 들여쓰기 스타일 사용:

    {
    

    "settings": {

    "indent": 2,

    "useTabs": false

    }

    }

    2. 자동화

    자동 beautification 설정:

    package.json:
    {
    

    "scripts": {

    "format": "prettier --write "/.json""

    }

    }

    pre-commit hook:
    #!/bin/sh
    

    # .git/hooks/pre-commit

    FILES=$(git diff --cached --name-only --diff-filter=ACM | grep '.json$')

    if [ -n "$FILES" ]; then

    echo "$FILES" | xargs prettier --write

    echo "$FILES" | xargs git add

    fi

    3. 환경별 설정

    개발:
    • Beautified JSON
    • 주석 허용 (JSONC)
    • 상세 출력

    프로덕션:
    • 압축 JSON
    • 주석 없음
    • 최소 크기

    일반적인 문제

    1. 유니코드 문자

    문제:
    {
    

    "name": "홍길동"

    }

    해결:
    # Python
    

    json.dumps(data, ensure_ascii=False)

    // JavaScript - 기본적으로 OK
    

    JSON.stringify(data)

    2. 대용량 숫자

    문제:

    정밀도 손실

    해결:
    JSON.stringify(data, (key, value) => {
    

    if (typeof value === 'number' && value > Number.MAX_SAFE_INTEGER) {

    return value.toString();

    }

    return value;

    });

    3. 순환 참조

    문제:
    const obj = {};
    

    obj.self = obj;

    JSON.stringify(obj); // 오류!

    해결:
    const seen = new WeakSet();
    

    JSON.stringify(obj, (key, value) => {

    if (typeof value === 'object' && value !== null) {

    if (seen.has(value)) return;

    seen.add(value);

    }

    return value;

    });

    성능 고려사항

    벤치마크

    | 도구 | 1KB | 100KB | 10MB |

    |------|-----|-------|------|

    | JSON.stringify | 0.1ms | 5ms | 500ms |

    | jq | 1ms | 20ms | 2s |

    | Python json | 0.2ms | 10ms | 1s |

    최적화 팁

  • 대용량 파일: 스트리밍 사용
  • 반복 작업: 결과 캐시
  • 프로덕션: 압축된 상태로 유지
  • 개발: 필요시에만 beautify
  • 결론

    JSON beautification은 개발 워크플로우의 필수 부분입니다. 온라인 도구, IDE 단축키 또는 프로그래밍 방식 솔루션을 사용하든 올바른 접근 방식은 요구 사항에 따라 달라집니다.

    빠른 팁:
    • ✓ IDE 자동 포맷팅 사용
    • ✓ 일관된 들여쓰기 유지
    • ✓ 커밋 전 beautify
    • ✓ 개발에는 beautified, 프로덕션에는 압축

    깨끗하고 읽기 쉬운 JSON으로 행복한 코딩하세요!

    Share:

    관련 글

    Read in English