둘의 구분
1. 자바스크립트 오브젝트(JSO)
{name:"John", age:31, city:"New York"}
2. JSON
{"name":"John", "age":31, "city":"New York"}
둘의 대표적인 차이는 필드명에 큰따옴표(" ")를 이용하냐 하지 않냐이다.
JSON의 선언 및 활용
<script>
const myObj = { name: "John", age: 31, city: "New York" };
const myJSON = JSON.stringify(myObj);
</script>
json은 우리가 한번에 선언할 수 있는 객체가 아니다.
그렇기때문에 일단 JSO로 선언을 해준 후 JSON.stringify를 통해 myJSON 이라는 객체로 선언해주었다.
<script>
const myJSON = '{"name":"John", "age":31, "city":"New York"}';
const myObj = JSON.parse(myJSON);
</script>
반대로 우리가 이것을 다시 JSO로 돌려주고 싶을땐 JSON.parse를 사용해주면 된다.
사용할때의 차이
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<script>
$(document).ready(function() {
$("#btn1").click(function() {
var Obj1 = {"name":"김김김","age":99,"level":255};
var JSON1 = JSON.stringify(Obj1);
$("#testing").html(JSON1);
});
$("#btn2").click(function() {
var Obj1 = {"name":"김김김","age":99,"level":255};
var JSON1 = JSON.stringify(Obj1);
$("#testing").html(Obj1.name);
});
});
</script>
<h1>제이슨을 연습해보겟어요~</h1>
<button type="button" id="btn1">눌러봐~ JSON1</button>
<button type="button" id="btn2">눌러봐~ obj1</button>
<div id="testing">뭘봐</div>
</body>
</html>
가장 중대한 차이점으로는 JSO는 각 필드를 불러와서 사용 할 수 있으나, JSON은 필드를 불러올 수 없고, 단 하나의 객체로서만 불러 올 수 있다.
이렇게 보듯이 우리가 JSON의 필드를 사용하고 싶다면 다시 parse를 이용하여 JSO로 만들어 주어야 따로 값을 불러올 수 있다.
'Web > JSP국비지원 수업 정리' 카테고리의 다른 글
다른 컴퓨터의 DB에 MYSQL로 원격 접속하기 (1) | 2023.07.20 |
---|---|
<input>의 attribute pattern (유효성 검사) (0) | 2023.07.10 |
제이쿼리를 이용한 form의 attribute 설정 (0) | 2023.07.10 |
jsp-Session (0) | 2023.07.07 |
Web 수업(servlet ) (0) | 2023.07.03 |