jquery json 예제

■ json object 만들기 1 – 배열 object a, b를 갖는 JSON(tmplObj) 객체를 생성

var tmplObj = new Object();
var tmpArr;

tmpArr         = ['a1','a2','a3'];
tmplObj.a     = tmpArr;

tmpArr         = ['b1','b2','b3'];
tmplObj.b     = tmpArr;

console.log( "json object : " + JSON.stringify(tmplObj) );
//결과 : json object : {"a":["a1","a2","a3"],"b":["b1","b2","b3"]}

 

■ json object 만들기 2 – 익명 배열(?)을 갖는 JSON(tmplObj) 객체를 생성(push 함수)

var tmplObj = new Array();
var tmpArr;

tmpArr = ['a1','a2','a3'];
tmplObj.push(tmpArr);

tmpArr = ['b1','b2','b3'];
tmplObj.push(tmpArr);

console.log( "json object : " + JSON.stringify(tmplObj) );
//결과 : json object : [["a1","a2","a3"],["b1","b2","b3"]]

 

■ json 배열에서 자식 삭제(delete)

var tmpArr = ['a1','a2','a3'];

console.log( "삭제 전 : " + JSON.stringify(tmpArr) );
// 삭제 전 : ["a1","a2","a3"]

delete tmpArr[1];    // 2번째 항목 삭제
console.log( "삭제 후 : " + JSON.stringify(tmpArr) );
// 삭제 후 : ["a1",null,"a3"]

 

■ json Object에서 자식 삭제(delete)

var tmpObj = new Object();
var tmpArr;

tmpArr = ['a1','a2','a3'];
tmpObj.a = tmpArr;

tmpArr = ['b1','b2','b3'];
tmpObj.b = tmpArr;

console.log( "삭제 전 : " + JSON.stringify(tmpObj) );
// 삭제 전 : {"a":["a1","a2","a3"],"b":["b1","b2","b3"]}

delete tmpObj.a;    // a 삭제
console.log( "삭제 후 : " + JSON.stringify(tmpObj) );
// 삭제 후 : {"b":["b1","b2","b3"]}

 

■ key가 없고 배열 첨자만 있는 jquery each문

var tmpArr    = ['a1','a2','a3'];

$.each(tmpArr, function(idx, val) {
    console.log( idx + " : " + val );
});

//결과
0 : a1
1 : a2
2 : a3

 

■ key가 있는 jquery each문

var tmpObj = new Object();
var tmpArr;

tmpArr = ['a1','a2','a3'];
tmpObj.a = tmpArr;

tmpArr = ['b1','b2','b3'];
tmpObj.b = tmpArr;

console.log( "tmpObj : " + JSON.stringify(tmpObj) );
$.each(tmpObj, function(key, val) {
    console.log( key + " : " + val );
});

// 결과
tmpObj : {"a":["a1","a2","a3"],"b":["b1","b2","b3"]}
a : a1,a2,a3
b : b1,b2,b3

 
 

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다