View

JSON - {Key : Value}

jaeeH 2022. 2. 21. 10:40

 

 

JSON

: JavaScript 객체 문법을 따르는 문자 기반 데이터 포맷

 

 

 

JSON의 구조

1. Name/Value 쌍의 모음 (object, record, 구조체, dictionary, hash table, key list, 연관된 array)

 

2. 정렬된 Value의 리스트 (array, vector, list, sequence)

    +JSON 객체를 넣을 수도 있음 [ {"name" : "Molcule Man", "age" : 29} , {"name" : "Madame Uppercut", "age" : 39} ]

 

 

Value로 저장 가능한 데이터형

 

 

 

예제

{
  "squadName": "Super hero squad",
  "homeTown": "Metro City",
  "formed": 2016,
  "secretBase": "Super tower",
  "active": true,
  "members": [
    {
      "name": "Molecule Man",
      "age": 29,
      "secretIdentity": "Dan Jukes",
      "powers": [
        "Radiation resistance",
        "Turning tiny",
        "Radiation blast"
      ]
    },
    {
      "name": "Madame Uppercut",
      "age": 39,
      "secretIdentity": "Jane Wilson",
      "powers": [
        "Million tonne punch",
        "Damage resistance",
        "Superhuman reflexes"
      ]
    },
    {
      "name": "Eternal Flame",
      "age": 1000000,
      "secretIdentity": "Unknown",
      "powers": [
        "Immortality",
        "Heat Immunity",
        "Inferno",
        "Teleportation",
        "Interdimensional travel"
      ]
    }
  ]
}

점/브라켓 표현법을 통해 객체 내 데이터에 접근 가능

superHeros.homeTown
superHeros['active']

Property명과 array 인덱스를 통해 하위 데이터에 접근하기

superHeroes['members'][1]['powers'][2]	//Superhuman reflexes

 

 

Notes

  • JSON은 Property만 담을 수 있음. 메소드는 X
  • String과 Property의 이름 작성 시 큰 따옴표(")만을 사용해야 함
  • 콤마/콜론을 잘못 배치하면 JSON 파일이 작동하지 않을 수 있음 (JSONLint : JSON 유효성 검사 어플리케이션)
  • JSON 내부에 포함할 수 있는 모든 형태의 데이터 타입을 취할 수 있음
  • 따옴표로 묶인 문자열만이 Property로 사용될 수 있음

 

 

 

 

 

JSON 관련 메소드

JSON.stringfy

: 객체를 JSON으로 바꿔줌

(☞JSON-encoded / serialized / stringfied object로 변환한다)

let student = {
    name: 'John',
    age: 30,
    isAdmin: false,
    courses: ['html', 'css', 'js'],
    married: null
};

let json = JSON.stringfy(stuendt);

alert(typeof json);	//String

alert(json);
/*
{
    "name": "John",
    "age": 30,
    "isAdmin": false,
    "courses": ["html", "css", "js"],
    "married": null
}
*/

숫자, 문자열, Boolean, Array 데이터형의 인코딩

alert(JSON.stringfy(1));	//1
alert(JSON.stringfy('test'));	//"test"
alert(JSON.stringfy(true));	//true
alert(JSON.stringfy([1,2,3]));	//[1,2,3]

JSON.stringfy 호출 시 무시되는 Property

  • 함수 property (메소드)
  • 심볼형 property (Key가 symbol인 property)
  • Value가 undefined인 property
let user = {
    sayHi() {	//무시
    	alert("Hello");
    },
    [Symbol("id")]: 123,	//무시
    something: undefined	//무시
};

alert(JSON.stringfy(user));	//{} (빈 객체 출력)

 

 

 

JSON.parse

: JSON을 객체로 바꿔줌

Syntax

let value = JSON.parse(str, [reviver]);

str : JSON 형식의 문자열

reviver : 모든 (Key, Value) 쌍을 대상으로 호출되는 function(Key, Value) 형태의 함수로 값을 변경 가능

//문자열로 반환된 배열
let numbers = "[0,1,2,3]";
numbers = JSON.pares(numbers);
alert(numbers[1]);	//1

중첩 객체에 사용 가능

let userData = '{"name": "John", "age": 35, "isAdmin": fales, "friends": [0,1,2,3]}';
let user = JSON.parse(userData);
alert(user.friends[1]);	//1

 

 

 

 

 

 

※ 출처

1. https://stackoverflow.com/questions/383692/what-is-json-and-what-is-it-used-for

 

What is JSON and what is it used for?

I've looked on Wikipedia and Googled it and read the official documentation, but I still haven't got to the point where I really understand what JSON is, and why I'd use it. I have been building

stackoverflow.com

2. https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/JSON

 

JSON으로 작업하기 - Web 개발 학습하기 | MDN

JavaScript Object Notation (JSON)은 Javascript 객체 문법으로 구조화된 데이터를 표현하기 위한 문자 기반의 표준 포맷입니다. 웹 어플리케이션에서 데이터를 전송할 때 일반적으로 사용합니다(서버에서

developer.mozilla.org

3. https://chaengstory.tistory.com/74

 

[JSON] JSON 핸들링 정리

JSON(제이슨 , JavaScript Object Notation) 객체를 표현하는 방식으로 속성-값 쌍으로 이루어진 데이터를 전달하고 인간이 읽을 수 있는 데이터 교환용으로 설계된 개방형 표준 포맷이다. JSON의 장점 1.데

chaengstory.tistory.com

4. https://ko.javascript.info/json#ref-1496

 

JSON과 메서드

 

ko.javascript.info

 

 

 

 

 

 

'JavaScript > Js Basic' 카테고리의 다른 글

호이스팅과 var, let, const의 차이  (0) 2022.01.20
Share Link
reply
«   2025/09   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30