2012-10-03 3 views
0

완전히 초보자입니다. jquery 라이브러리가 있습니다. json을 반환하는 api를 호출합니다. jQuery 라이브러리 내에서 parseJSON 함수를 사용하여 구문 분석하고 싶습니다. 간단히 말해서, 나는 그렇게하는 법을 모른다.JSON jquery로 구문 분석

parseJSON: function(data) { 
    if (typeof data !== "string" || !data) { 
     return null; 
    } 

    // Make sure leading/trailing whitespace is removed (IE can't handle it) 
    data = jQuery.trim(data); 

    // Attempt to parse using the native JSON parser first 
    if (window.JSON && window.JSON.parse) { 
     return window.JSON.parse(data); 
    } 

    // Make sure the incoming data is actual JSON 
    // Logic borrowed from http://json.org/json2.js 
    if (rvalidchars.test(data.replace(rvalidescape, "@") 
     .replace(rvalidtokens, "]") 
     .replace(rvalidbraces, ""))) { 

     return (new Function("return " + data))(); 

    } 
    jQuery.error("Invalid JSON: " + data); 
}, 

가 어떻게 그 통해 내 JSON을 보내려면 어떻게합니까 : 나는 jQuery 라이브러리 내에서 기능을 찾을 수 있습니다

는, 그렇게 보이는? 당신이 jQuery.getJSON 기능을 사용하는 경우

답변

2
var obj = jQuery.parseJSON(yourJsonObj); 
1

, 당신은 당신의 API 엔드 포인트에 액세스하고 응답 한 호출에 모든 구문 분석 할 수 있습니다.

$.getJSON("/my_resource.json", function(data) { 
    // Use data here 
}); 
0

jQuery의 parseJSON() 함수는 json을 javascript 객체로 변환합니다. 예를 들어 당신의 JSON 경우

: 당신이 parseJSON를 사용할 때

{ "firstname" : "john", "lastname" : "doe" } 

는, 당신과 같이 속성에 액세스 할 수 있습니다 : 당신이 시작해야

var json = '{ "firstname" : "john", "lastname" : "doe" }'; 
var person = jQuery.parseJSON(json); 

console.log(person.firstname); //will show john 
console.log(person.lastname); //will show doe 

합니다. 자세한 내용은 여기에서 문서를 읽어보십시오. http://api.jquery.com/jQuery.parseJSON/

2

jQuery AJAX 명령을 사용하는 경우 대부분 데이터 유형 매개 변수를 사용합니다. dataType을 'json'으로 설정하면 반환 된 데이터가 자동으로 구문 분석됩니다.

$.ajax({ 
    url: url, 
    dataType: 'json', 
    data: data, 
    success: callback 
}); 

이 경우 데이터는 결국 AJAX 호출에서 반환 된 JSON을 기반으로하는 개체가됩니다.