JSON 개념

JSON (JavaScript Object Notation)은 자바스크립트 객체 문법으로 구조화된 데이터를 전송하는 데이터 교환 형식입니다.

JSON 특징

데이터 구조

키-값 쌍과 배열을 사용하여 데이터를 표현하므로 구조화된 데이터를 계층적 방식으로 구성할 수 있습니다.

{
  "person": {
    "name": "John Doe",
    "age": 30,
    "city": "New York",
    "isStudent": false,
    "grades": [85, 90, 78]
  }
}

언어 독립성

JavaScript에 국한되지 않고 다양한 프로그래밍 언어에서 광범위하게 지원되므로 서로 다른 시스템 간의 상호 운용이 가능합니다.


다음과 같은 Data.json 파일이 있다고 할 때 JavaScript과 Python에서 다음과 같이 파싱 할 수 있습니다.

{
  "name": "John Doe",
  "age": 30,
  "city": "New York"
}

JavaScript 에서

const fs = require('fs');

// JSON 파일 읽기
const jsonString = fs.readFileSync('data.json', 'utf8');

// JSON을 JavaScript 객체로 Parse
const parsedObject = JSON.parse(jsonString);

// 데이터 접근
console.log(parsedObject.name);  // John Doe
console.log(parsedObject.age);   // 30
console.log(parsedObject.city);  // New York

Python에서

import json

# JSON 파일 읽기
with open('data.json', 'r') as file:
    json_string = file.read()

# Json을 딕셔너리 객체로 파싱
parsed_dict = json.loads(json_string)

# 데이터 접근
print(parsed_dict['name'])  # John Doe
print(parsed_dict['age'])   # 30
print(parsed_dict['city'])  # New York

가독성

JSON은 간단하고 읽기 쉬운 구문이 특징입니다.

다음은 동일한 데이터를 XML과 JSON 으로 표현한 예입니다.

XML

<library>
  <book>
    <title>The Great Gatsby</title>
    <author>F. Scott Fitzgerald</author>
    <publicationYear>1925</publicationYear>
    <genres>
      <genre>Fiction</genre>
      <genre>Classic</genre>
    </genres>
    <availability>
      <physicalCopy>Yes</physicalCopy>
      <eBook>Yes</eBook>
      <audiobook>No</audiobook>
    </availability>
  </book>
  <book>
    <title>To Kill a Mockingbird</title>
    <author>Harper Lee</author>
    <publicationYear>1960</publicationYear>
    <genres>
      <genre>Fiction</genre>
      <genre>Classic</genre>
    </genres>
    <availability>
      <physicalCopy>Yes</physicalCopy>
      <eBook>Yes</eBook>
      <audiobook>Yes</audiobook>
    </availability>
  </book>
  <book>
    <title>Introduction to Algorithms</title>
    <author>Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein</author>
    <publicationYear>1990</publicationYear>
    <genres>
      <genre>Non-Fiction</genre>
      <genre>Computer Science</genre>
    </genres>
    <availability>
      <physicalCopy>Yes</physicalCopy>
      <eBook>Yes</eBook>
      <audiobook>No</audiobook>
    </availability>
  </book>
</library>

JSON

{
  "books": [
    {
      "title": "The Great Gatsby",
      "author": "F. Scott Fitzgerald",
      "publicationYear": 1925,
      "genres": ["Fiction", "Classic"],
      "availability": {
        "physicalCopy": true,
        "eBook": true,
        "audiobook": false
      }
    },
    {
      "title": "To Kill a Mockingbird",
      "author": "Harper Lee",
      "publicationYear": 1960,
      "genres": ["Fiction", "Classic"],
      "availability": {
        "physicalCopy": true,
        "eBook": true,
        "audiobook": true
      }
    },
    {
      "title": "Introduction to Algorithms",
      "author": "Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein",
      "publicationYear": 1990,
      "genres": ["Non-Fiction", "Computer Science"],
      "availability": {
        "physicalCopy": true,
        "eBook": true,
        "audiobook": false
      }
    }
  ]
}

데이터의 유연성

문자열, 숫자, boolean, 배열 및 객체와 같은 기본 데이터 유형을 지원하여 데이터 표현의 유연성을 제공합니다.

아래 JSON 데이터의 예를 보면 name은 string, age는 숫자, isStudent는 boolean, grades는 배열, address는 객체, hobbies는 배열로 다양한 데이터 유형이 표현된 것을 볼 수 있습니다.

{
  "name": "John Doe",
  "age": 30,
  "isStudent": false,
  "grades": [85, 90, 78],
  "address": {
    "city": "New York",
    "zipcode": "10001"
  },
  "hobbies": ["reading", "traveling"]
}

Schemaless (유연한 구조)

사전 정의된 스키마가 필요하지 않으므로 엄격한 제약 없이 동적이고 유연한 데이터 구조가 가능합니다.

아래 JSON을 보면, features 키에 대한 value들이 다양하 형태로 들어 간 것을 확인 할 수 있습니다. 이와 같이 다양한 정보를 동적으로 표현 할 수 있습니다.

{
  "products": [
    {
      "type": "phone",
      "brand": "Samsung",
      "model": "Galaxy S21",
      "features": {
        "color": "black",
        "storageGB": 128
      }
    },
    {
      "type": "laptop",
      "brand": "Dell",
      "model": "XPS 13",
      "features": {
        "processor": "Intel i7",
        "ramGB": 16
      }
    },
    {
      "type": "headphones",
      "brand": "Sony",
      "model": "WH-1000XM4",
      "features": {
        "wireless": true,
        "color": "silver"
      }
    }
  ],
  "location": "electronics_store",
  "manager": "Alex"
}

하지만 개발이나 분석을 하다 보면 이런 유연한 구조는 잠재적인 단점 또한 가지고 있다는 것을 알게 됩니다.

사전 정의된 스키마가 없다는 것은 데이터 구조에 대한 엄격한 검증이 없다는 것을 의미 합니다. 이것은 예상치 못한 누락 또는 오류가 있을 수 있다는 것을 의미 합니다.

또한 스키마가 없으면 개발 프로세스 초기에 오류를 포착하기가 더 어려워집니다. 이로 인해 애플리케이션에 잠재적인 문제가 발생할 수 있습니다.

그리고 문서화 해야 하는 경우, 데이터의 구조와 유형을 이해하기 위한 문서화 작업에 부담이 갈 수 있습니다.

특히 복잡한 애플리케이션에서 잘 정의된 스키마나 하이브리드 접근 방식을 사용하면 데이터 일관성, 유효성 검사 및 상호 운용성 측면에서 이점을 제공할 수 있습니다.

JSON 자료형

JSON에서 사용 가능한 자료형은 String, 수, Boolean, Array, Object, Null이 있습니다.

JSON 활용

JSON은 프로그래밍 언어와 프레임워크 독립적이므로, 서로 다른 시스템 간의 데이터를 교환하기 좋습니다. 또한 아래처럼 시스템을 구성하는 configuration 파일에 사용될 수 있습니다.

{
  "server": {
    "port": 8080,
    "host": "localhost"
  },
  "database": {
    "username": "admin",
    "password": "securePassword"
  }
}

Leave a Comment

목차