πŸ“JSON.stringify ν•¨μˆ˜ 와 JSON.parse ν•¨μˆ˜

10_2pangΒ·2023λ…„ 6μ›” 5일
1

βš½οΈνŠΈλŸ¬λΈ”μŠˆνŒ…

λͺ©λ‘ 보기
49/94
post-thumbnail

πŸ‘¨β€πŸ’»Β μ‚¬κ±΄


μ›ν‹°λ“œ μ˜¨λ³΄λ”© μ±Œλ¦°μ§€ κ³Όμ œμ—μ„œ 둜그인 κΈ°λŠ₯ κ΅¬ν˜„ 과제λ₯Ό μˆ˜ν–‰ν•˜λ©΄μ„œ 토큰 뢀뢄을 μ„€μ •ν• λ•Œ, stringify ν•¨μˆ˜λ₯Ό ν†΅ν•˜μ—¬ JSON ν˜•μ‹μ˜ λ¬Έμžμ—΄λ‘œ λ°˜ν™˜ν•˜λŠ” 과정이 μžˆμ—ˆλ‹€. κ·Έ κ³Όμ •μ—μ„œ JSON ν•¨μˆ˜λ‘œ 자주 μ‚¬μš©ν•˜λŠ” stringify ν•¨μˆ˜μ™€ parse ν•¨μˆ˜μ— λŒ€ν•΄ λͺ…ν™•νžˆ μ§‘κ³  λ„˜μ–΄κ°€κ³  μ‹Άμ—ˆλ‹€.

βœ…Β ν•΄κ²°


  • JSON.stringify
    • μžλ°”μŠ€ν¬λ¦½νŠΈ 객체λ₯Ό JSON 파일의 ν˜•νƒœμ˜ λ¬Έμžμ—΄λ‘œ λ°˜ν™˜ν•˜λŠ” ν•¨μˆ˜μ΄λ‹€.

      JSON.stringify(value, replacer, space)
      // value - λ³€ν™˜ν•  μžλ°”μŠ€ν¬λ¦½νŠΈ 객체
      // replacer - 선택 μ˜΅μ…˜μœΌλ‘œ, ν•¨μˆ˜ ν˜Ήμ€ λ°°μ—΄μ˜ 값을 ν•œλ²ˆ κ±°μ³μ„œ ν•„μš”ν•œ λ‚΄μš©λ§Œμ„ λ°˜ν™˜ν•˜κ³ μž ν• λ•Œ
      // space - λ¬Έμžμ—΄λ‘œ λ°˜ν™˜μ‹œ, 곡백을 μ‚¬μš©ν•˜κ³  μ‹Άμ„λ•Œ μ‚¬μš©ν•œλ‹€.
    • value

      const obj = {name: "John", age: 30, city: "New York"};
      const jsonString = JSON.stringify(obj);
      
      console.log(jsonString); // {"name":"John","age":30,"city":"New York"}
    • replacer

      • λ°°μ—΄
        const obj = {name: "John", age: 30, city: "New York"};
        const jsonString = JSON.stringify(obj,["name"]);
        // λ°°μ—΄λ‘œ μ„€μ •λœ κ°’λ§Œ μΆ”μΆœ
        console.log(jsonString);// {"name":"John"}
      • ν•¨μˆ˜
        function replacer(key, value) {
        	if (typeof value === "string") {
        		return undefined;
        	}
        	return value;
        }
        const obj = {name: "John", age: 30, city: "New York"};
        const jsonString = JSON.stringify(obj,replacer);
        // replacer ν•¨μˆ˜λ₯Ό ν•œλ²ˆ κ±°μ³μ„œ 좜λ ₯
        console.log(jsonString);// {"age":30}
    • space

      const obj = {name: "John", age: 30, city: "New York"};
      const jsonString = JSON.stringify(obj,null,5);
      
      console.log(jsonString);
      //κ²°κ³Όκ°’ 
      //{
      //     "name": "John",
      //     "age": 30,
      //     "city": "New York"
      //}
  • JSON.parse
    • μžλ°”μŠ€ν¬λ¦½νŠΈ 객체둜 λ³€ν™˜ν•  수 μžˆλŠ” JSON λ¬Έμžμ—΄μ„ νŒŒμ‹±ν•˜μ—¬ μžλ°”μŠ€ν¬λ¦½νŠΈ 객체둜 λ³€ν™˜ν•©λ‹ˆλ‹€.
      JSON.parse(text, reviver)
      // text - νŒŒμ‹±ν•  λ¬Έμžμ—΄
      // reviver - μ„€μ •λœ λ§€κ°œλ³€μˆ˜ ν•¨μˆ˜λŠ” νŒŒμ‹±ν•  JSON λ¬Έμžμ—΄μ˜ 각 ν‚€/κ°’ μŒμ„ μ²˜λ¦¬ν•˜λŠ” 방법을 μ •μ˜ν•©λ‹ˆλ‹€.
      //           이 ν•¨μˆ˜λŠ” νŒŒμ‹± κ²°κ³Ό 객체의 각 속성값을 λŒ€μ²΄ν•˜κ±°λ‚˜ ν•„ν„°λ§ν•˜λŠ” 데 μ‚¬μš©λ©λ‹ˆλ‹€.
      • μ˜ˆμ‹œ
        const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
        const obj = JSON.parse(jsonString);
        
        console.log(obj.name); // "John"
        console.log(obj.age); // 30
        console.log(obj.city); // "New York"
profile
μ£Όλ‹ˆμ–΄ ν”„λ‘ νŠΈμ—”λ“œ 개발자 이광렬 μž…λ‹ˆλ‹€ 🌸

0개의 λŒ“κΈ€