예제로 사용할 json 데이터는 다음과 같다.
{
"SrchQueryResult": {
"about": "sreachAnimalResult",
"resultQuery": [{
"id": "mammal",
"field": "포유류검색영역",
"detailQuery": {
"count": "2",
"file": [{
"animalId": "dog",
"animalName": "강아지",
"animalImgPath": "c:fakepath",
"animalContent": "강아지 상세내용"
},
{
"animalId": "cat",
"animalName": "고양이",
"animalImgPath": "c:fakepath2",
"animalContent": "고양이 상세내용"
}
]
}
}]
}
}
위의 데이터를 javascript에서 ajax로 가져온다면 다음과 같이 사용하면 된다.
$.ajax({
type: "POST"
,url:"/animal/search.jsp" // json 경로
,dataType:"json"
,data: {
LIST : $("#list").val()
}
,success : function(response, textStatus, xhr){
var jsonStringify = JSON.stringify(response);
var animalList = JSON.parse(jsonStringify);
var animalStr = "";
for(var cnt = 0; cnt < animalList.SrchQueryResult.resultQuery.length; cnt++) {
for(var fileCnt = 0; fileCnt < animalList.SrchQueryResult.resultQuery[cnt].detailQuery.file.length; fileCnt++) {
animalStr += animalList.SrchQueryResult.resultQuery[cnt].detailQuery.file[fileCnt].animalId;
animalStr += " : ";
animalStr += animalList.SrchQueryResult.resultQuery[cnt].detailQuery.file[fileCnt].animalName;
animalStr += "<br>";
}
}
...... // 이후 코드 작성
}
,error: function(xhr, textStatus, error){
alert("code : " + xhr.status + "\nmessage : " + xhr.responseText + "\nerror : "+error);
}
});
이상하게 곧바로 JSON.parse()를 사용하면 데이터가 안가져와져서 JSON.stringify 한 다음 JSON.parse 를 사용하였다.
json 은 처음 사용해봤는데 ajax와 같이 사용하고 json 데이터 형식도 길어져서 데이터 가져올 때 살짝 헤맸다.
아래는 알아두면 유용한 사이트.
json 문법 체크 : https://jsonlint.com/
json 데이터를 보기 좋게 정렬 : http://json.parser.online.fr/
json 공백 제거 : http://jsonviewer.stack.hu/