본문 바로가기

IT/Web

[Javascript] JSON 정리

대부분의 웹 개발자들은 과거의 Javascript 문법에 익숙해져 있고 나도 그렇다.

 

function funcOld(){}

 

하지만 이제는 객체지향의 문법 형태를 많이 사용하게 되는데 

 

var newOne = {

funcNew:function(){}

};

 

newOne.funcNew();

newOne 객체의 메소드라는 느낌이다.

 

간단하게 객체답게 만들어 보면

 

 <script>

var customer = {

id:111,

name:' ',

getName:function(){

alert(this.name);

return this.name;

},

setName:function(name){

this.name = name;

}

};

</script>

<body>

<input type="button" value="설정" onClick="customer.setName('홍길동')"/>

<input type="button" value="가져오기" onClick="customer.getName()"/>

</body>

 

customer의 객체를 만들어 실행해 볼 수 있겠다.

customer 객체는 JSON의 형태로 구성되어 있는데

각 행은 자바스크립트의 행 구분인 세미콜론이 아닌 콤마로 구분되어 있다.

 

JSON에서는 [ { , " ' 의 형태로 구성된 문자열 데이터 형태로 XML에 비해 짧고 간단하게 데이터를 구성할 수 있다.

 

 

 <script>

var customer = {

id:111,

name:'-',

getName:function(){

return this.name;

},

setName:function(name){

this.name = name;

}

};

var btnSet;

var btnGet;

window.onload = function(){

btnSet = document.querySelector('#btnSet');

btnGet = document.querySelector('#btnGet');

btnSet.onclick=function(){

customer.setName('홍길동');

};

btnGet.onclick=function(){

alert(customer.getName());

};

}

</script>

<body>

<input type="button" id="btnSet" value="설정"/>

<input type="button" id="btnGet" value="가져오기"/>

</body>

 

위는 HTML의 엘리먼트에서 정의했던 이벤트를 Javascript의 객체로 모두 구현한 것이다.

 

JSON 데이터 처리에 대해 설명하고자 한다.

 

위에서 말해듯이 JSON은  [ { , " ' 의 형태로 구성된 문자열 데이터 형태라고 하였다.

 

var temp = {name:'홍길동', id:1234};

 

var temp = [{name:'홍길동', id:1234},{name:'홍길순', id:5678}];

 

var temp = [{name:'홍길동', id:1234, 

method:[{year:'1990', run:'fast', size:'small'},{year:1991', run:'fastest', size:'medium'}]},

{name:'홍길순',id:5678, 

method:[{year:1992', run:'fastest', size:'medium'}{year:1993', run:'fast', size:'big'}]}];

 

JSON의 기본적인 데이터의 처리는 이런 기호의 조합이다.

이런 처리를 위해 문자열의 JSON 변환과 JSON을 문자열로 변환하는 기능( JSON.stringify() )이 필요하다.