다연이네

[days14] JSON 개요 본문

JSP

[days14] JSON 개요

 다연  2021. 1. 14. 12:46
반응형

https://www/json.org/ 즐겨찾기

JSON 개요


  ㄱ.  [J]ava[S]cript [O]bject  [N]otiaion
       자바스크립트 객체 표기법


  ㄴ.  클라이언트와 서버 간에 데이터를 교환하는 용도
       js 객체 -> 텍스트(문자열) 변환   ->   요청URL?파라미터 전달
              JSON.stringify(person);  


  ㄷ.  XML보다 사람+기계한테 JSON이 더 간결(성능)/쉽다. 


  ㄹ.  클라이언트 -> 서버 데이터 보내기

 <script> 
    var person = { 
     name: "john" 
     ,age:10 
     ,city:"seoul" 
    }; //자바스크립트 객체 
     
    //객체를 전달하고싶다 
      //location.href = "ex01_02.jsp?person="+person; //불가능 (js object바로 사용 불가) 
    //텍스트로 변경후에 가능 (제이슨)   JSON. stringify() 
      var personJSON = JSON.stringify(person);  
      location. href = "ex01_02.jsp?person="+personJSON;     
 </script> 


  ㅁ.  클라이언트 -> 서버로 js객체를 JSON으로 변환해서 파라미터로 전달했고  
       서버에서는 JSON 텍스트(문자열) 파라미터를 js 객체로 변환시켜서 사용해야 된다면
       JSON -> js Object로 변환하는 메소드 : JSON. parse()

  <script> 
    var personJSON = '{ "name": "john", "age":10, "city":"seoul"}'; 
    //JSON에서 사용되는 자료형 (10에는 따옴표 안붙힘) 
    var person = JSON.parse(personJSON); 
    document.getElementById("demo").innerHTML = person.name 
  </script> 


   ㅂ.  js Object를 JSON으로 변환해서 그 문자열 데이터를  로컬 저장소에 저장

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
   $(document).ready(function (){     
   });
</script>
</head>
<body>
<p id="demo"></p>

<button onclick="getName();">person.name</button>

<script>
//1. js Object -> JSON 변환
var person = {
		name: "john"
		,age:10
		,city:"seoul"
};
var personJSON = JSON.stringify(person); 
//{"name":"john","age":10,"city":"seoul"}

//2. 로컬 저장소에 JSON 저장
localStorage.setItem("personJSON", personJSON);
</script>

<script>
function getName() {
	var receivePersonJSON = localStorage.getItem("personJSON"); //json
	var person2 = JSON.parse(receivePersonJSON); //json -> js
	document.getElementById("demo").innerHTML = person2.name;
}
</script>
</body>
</html>


   ㅅ.  JSON 형식
        - js 객체 표기법 구문에서 파생되어졌다. 
          js Object       var person = {속성명:속성값, 속성명:속성값, . . . }
        -                                         name:value 쌍
          var personJSON = '{ "name": "john", "age":10, "city":"seoul"}';
        -                                데이터들은 콤마로 구분
        -                            {                                                   } 중괄호 표기
        - JSON 자료형으로 배열을 표기할 때 - 대괄호[]를 사용한다. 
           예) 
             1) JS Object
                 var person = { name:"admin" }
             2) JSON                  이름          값
                 var person = '{ "name":"admin", "child":{"name":"dayeon", "age":24}
                                           , "color":["red","blue","green"] 
                                           , "gender" : "true"
                                           , "friend" : "null"
                                       }'
                 
    ㅇ.  JSON 값(value)으로 사용되는 자료형(데이터 타입) 
        1) 문자열
        2) 숫자
        3) 객체 {}
        4) 배열 []
        5) "true"/"false"
        6) "null"
    
    ㅈ.   js에서는 작은따옴표, 큰 따옴표를 사용 가능
         JSON: 큰 따옴표 사용           { "name":"admin" }
     
    ㅊ.  JSON 파일
        1) 확장자          . json
        2) MIME 유형  "application/json"
        
         예)

{
    "name":"John",
    "age":31,
    "pets":[
        { "animal":"dog", "name":"Fido" },
        { "animal":"cat", "name":"Felix" },
        { "animal":"hamster", "name":"Lightning" }
    ]
}


 
    ㅋ.  JSON과 XML 비교
         eXtemsible Markup Language
        1) ex02_dept. xml

<?xml version="1.0" encoding="UTF-8"?>
<departments>  <!-- 태그는 내맘대로 만들기(없는 태그 가공해서) -->
 		10	 ACCOUNTING	NEW YORK
		20	 RESEARCH		DALLAS
		30	 SALES				CHICAGO
		40	 OPERATIONS	BOSTON
		
		<dept>
		  <deptno>10</deptno>
		  <dname>ACCOUNTING</dname>
		  <loc>NEW YORK</loc>
		</dept>
		<dept>
		  <deptno>20</deptno>
		  <dname>RESEARCH</dname>
		  <loc>DALLAS</loc>
		</dept>
		<dept>
		  <deptno>30</deptno>
		  <dname>SALES</dname>
		  <loc>CHICAGO</loc>
		</dept>
		<dept>
		  <deptno>40</deptno>
		  <dname>OPERATIONS</dname>
		  <loc>BOSTON</loc>
		</dept>
</departments>

        2) ex02_dept. json

{ 
  "departments":[
 	{"deptno":10, "dname":"ACCOUNTING", "loc":"NEW YORK"}
 	, {"deptno":20, "dname":"RESEARCH", "loc":"DALLAS"}
 	, {"deptno":30, "dname":"SALES", "loc":"CHICAGO"}
 	, {"deptno":40, "dname":"OPERATIONS", "loc":"BOSTON"}
 	]
}

 JSON > XML
     1) JSON이 XML보다 더 코딩이 짧다.
     2)             "                     간결하다.
     3)             "             읽기/쓰기가 더 쉽고 빠르다.
     4) JSON은 닫기 태그 x, JSON은 배열을 사용할 수 있다.
     
    많은 프로그래밍 언어에서 JSON과 XML을 모두 사용하고 있다.
    XMLHttpRequest 객체에서도 JSONXML을 모두 가져올 수 있다.
                                                   responseXML
                                       responseText
       예) 어제 배운 XMLHttpRequest를 사용해서 Ajax 처리 + JSON데이터 가져와보기

 

 

ex01_03_demo.json

{
    "name":"John",
    "age":31,
    "pets":[
        { "animal":"dog", "name":"Fido" },
        { "animal":"cat", "name":"Felix" },
        { "animal":"hamster", "name":"Lightning" }
    ]
}

위 파일을 가져와 pets의 name들 모두 출력하기  ( Fido,Felix,Lightning

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="">
<style>
</style>
<script>
   $(document).ready(function (){    
	   $("button").on("click", function(event) {
	   	 var xmlhttp  = new XMLHttpRequest();             //(1)
	   	 xmlhttp.onreadystatechange = function() {       //(4)
			if(this.readyState==4 && this.status ==200){
				var jsObj = JSON.parse(this.responseText); // json -> js 객체
				//$("#demo").html( jsObj.name + "/" + jsObj["age"]);
				// pets의 dog, cat, hamster  이름 출력
				$("#demo").html(function() {
					var data = [];
					for (var i = 0; i < jsObj.pets.length; i++) {
						data.push(jsObj.pets[i].name);
					}
					return data.join(",");
				});
			}
		};
		xmlhttp.open("GET", "ex01_03_demo.json", true); //(2)
		xmlhttp.send();                                                     //(3)
	   }); //click
   });//ready
</script>
</head>
<body>
<button>ajax+json test</button>
<p id="demo"></p>
</body>
</html>
반응형
Comments