티스토리 뷰

 

JSON

  • JavaScript Object Notation
  • 자바 스크립트의 객체 표기법
  • 문자 데이터

 

JSON 데이터 사용 방법

json 확장자를 가진 파일은 문자(string) 데이터이다.

json의 문자 데이터를 가지고 오면, 자동으로 변환되서 실제 객체 데이터처럼 출력이 된다.

 

 

1. Object to JSON - stringify(obj)

 

// JavaScript Object Notation

// 1. Object to JSON
// stringify(obj)
let json = JSON.stringify(true);
console.log(json);		// true

json = JSON.stringify(['apple', 'banana']);
console.log(json);      // ["apple", "banana"]

const rabbit = {
    name: 'tori',
    color: 'white',
    size: null,
    birthDate: new Date(),
    jump: () => {
        console.log(`${this.name} can jump!`);
    },
};

json = JSON.stringify(rabbit);
console.log(json);      // {"name":"tori","color":"white","size":null,"birthDate":"2022-03-29T13:22:54.943Z"}

json = JSON.stringify(rabbit, ['name', 'color']);
console.log(json);      // {"name":"tori","color":"white"}

// 좀 더 세밀하게 표현하고 싶을 때 콜백함수 이용.
json = JSON.stringify(rabbit, (key, value) => {
    console.log(`key: ${key}, value: ${value}`);
    return key === 'name' ? 'ellie' : value;
});
console.log(json);

console 출력

 

 

2. JSON to Object - parse(json)

 

// 2. JSON to Object
// parse(json)
console.clear();

json = JSON.stringify(rabbit);
console.log(json);
const obj = JSON.parse(json, (key, value) => {
    console.log(`key: ${key}, value: ${value}`);
    return key === 'birthDate' ? new Date(value) : value;
});
console.log(obj);

rabbit.jump();
// obj.jump();     => 에러 발생.
// Object를 JSON으로 변환할 때는 함수가 포함되지 않는다. (데이터만)
// 따라서 변환된 JSON객체를 다시 Object로 변환하면 함수 기능이 포함 되어있지 않다.

console.log(rabbit.birthDate.getDate());
console.log(obj.birthDate.getDate());

console 출력

 

 

 

 


유용한 사이트.

 

1. JSON Diff

서버에게 요청했을 때, 첫번째로 받아온 데이터와 두번째로 받아온 데이터가 어떤게 다른지 비교해준다.

문제를 디버깅할 때 유용하게 쓸 수 있다.

 

http://www.jsondiff.com/

 

JSON Diff - The semantic JSON compare tool

 

www.jsondiff.com

 

 

2. JSON Beautifier

서버에서 받아온 json을 format을 이쁘게 만들어준다.

 

https://jsonformatter.org/

 

Best JSON Formatter and JSON Validator: Online JSON Formatter

Online JSON Formatter / Beautifier and JSON Validator will format JSON data, and helps to validate, convert JSON to XML, JSON to CSV. Save and Share JSON

jsonformatter.org

 

 

3. JSON Parser

json 타입으로부터 Object형으로 어떻게 표기 되어지는지 쉽게 확인할 수 있다.

 

https://jsonparser.org/

 

JSON Parser - Best JSON Formatter | JSON Editor

The best JSON parser online helps you to converts json to a readable. You can do json formatter, json beautifier, json viewer, json editor.

jsonParser.org

 

 

4. JSON Validator

유효한 JSON 데이터인지 확인할 수 있다.

(json이 이상할 때 확인해보면 도움된다.)

 

https://tools.learningcontainer.com/json-validator/

 

Best free online JSON Validator

The JSON Validator(JSONLint) helps debugging JSON data by formatting and validating JSON data, JSON String and Json Objects so that it can easily find and read errors by human beings.

tools.learningcontainer.com

 

최근에 올라온 글
Total
Today
Yesterday