๐ 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 |