๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

TIL

JSON

 

๐Ÿ“Œ JSON์ด๋ž€?

 

JavaScript Object Notation

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐ์ฒด ๋ฌธ๋ฒ•์— ํ† ๋Œ€๋ฅผ ๋‘”, ๋ฌธ์ž ๊ธฐ๋ฐ˜์˜ ๋ฐ์ดํ„ฐ ๊ตํ™˜ ํ˜•์‹์„ ์˜๋ฏธํ•œ๋‹ค.

์ผ๋ฐ˜์ ์ธ JSON ๊ตฌ์กฐ๋Š” ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐ์ฒด ๋ฆฌํ„ฐ๋Ÿด ์ž‘์„ฑ๋ฒ•์„ ๋”ฐ๋ฅธ๋‹ค. 

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ ์›์‹œ ์ž๋ฃŒํ˜•์ธ ๋ฌธ์ž์—ด, ์ˆซ์ž, ๋ถˆ๋ฆฌ์–ธ์„ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๊ณ  ์ค‘์ฒฉ๋œ ๊ณ„์ธต ๊ตฌ์กฐ ๋˜ํ•œ ๊ฐ€์งˆ ์ˆ˜ ์žˆ๋‹ค.

 

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐ์ฒด ํ˜•ํƒœ์™€ ์™„์ „ํžˆ ๊ฐ™์ง„ ์•Š๋‹ค. ์ž‘์€ ๋”ฐ์˜ดํ‘œ'' ๊ฐ€ ์•„๋‹Œ ""๋งŒ ํ—ˆ์šฉ๋œ๋‹ค.

 

 

 

 

๐Ÿ“Œ ๋ฉ”์„œ๋“œ

 

1. JS ๊ฐ์ฒด๋ฅผ JSON ํ˜•ํƒœ๋กœ ์ „์†ก

2. JSON ํ˜•ํƒœ๋ฅผ JS ๊ฐ์ฒด ํ˜•ํƒœ๋กœ ์‚ฌ์šฉ

 

 

stringify() : ์ŠคํŠธ๋งํ™”์‹œํ‚จ๋‹ค. ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐ์ฒด๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ฐ”๊พผ๋‹ค.

console.log(JSON.stringify({ x: 5, y: 6 }));
// Expected output: "{"x":5,"y":6}"

console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
// Expected output: "[3,"false",false]"

console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }));
// Expected output: "{"x":[10,null,null,null]}" ์ง€์›์ด ์•ˆ ๋˜๋Š” ์ž๋ฃŒ๊ตฌ์กฐ๋„ ์žˆ๋‹ค.

console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// Expected output: ""2006-01-02T15:04:05.000Z""

 

 

 

parse() : Json ๋ฌธ์ž์—ด์„ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค. ๋„คํŠธ์›Œํฌ ํ†ต์‹ ์˜ ๊ฒฐ๊ณผ๋ฅผ ํ†ตํ•ด ๋ฐ›์•„์˜จ json ๋ฌธ์ž์—ด์„ ํ”„๋กœ๊ทธ๋žจ ๋‚ด๋ถ€์—์„œ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด js ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•  ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);

console.log(obj.count);
// Expected output: 42

console.log(obj.result);
// Expected output: true

 

 

 

 

๐Ÿ“Œ JSONPlaceholder : ๊ฐ€์งœ ์„œ๋ฒ„

import "./App.css";
import { useEffect, useState } from "react";

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts")
      .then((response) => {
        console.log();
        console.log("response.json()", response);
        return response.json();
      })
      .then((json) => {
        console.log("json", json);
        setData([...json]);
      });
  }, []);

  return (
    <div>
      {data.map((item) => {
        return (
          <div
            style={{
              border: "1px solid black",
              margin: "3px",
            }}
            key={item.id}
          >
            <ul>
              <li>userId : {item.userId}</li>
              <li>id : {item.id}</li>
              <li>title : {item.title}</li>
              <li>body : {item.body}</li>
            </ul>
          </div>
        );
      })}
    </div>
  );
}

export default App;

 

 

 

 

 

 

'TIL' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

ํ”„๋กœ์ ํŠธ ํšŒ๊ณ ๋ก  (0) 2023.07.06
React_์ด๋ฏธ์ง€ ํŒŒ์ผ ์—…๋กœ๋“œํ•˜๊ธฐ  (0) 2023.05.17
React_action creators, action values  (0) 2023.05.02
React_useDispatch, useSelector  (0) 2023.04.29
React_counter ๋งŒ๋“ค๊ธฐ  (0) 2023.04.28