2016-09-30 2 views
1

불필요한 AJAX 요청을 여러 번 피하기 위해 HTML의 숨겨진 요소에서 JSON을 사용합니다. JSON은 제대로 생성되지만 JQuery를 사용하여 처리 할 수 ​​없으므로 작업 할 수 있습니다.JQuery에서 HTML 데이터 속성을 JSON으로 변환하는 방법은 무엇입니까?

문제는 elem.data("json")이 문자열 대신 개체를 반환하므로 parseJSON은 문자열 시작 부분에 예기치 않은 o가 있다고 말합니다.

$(document).ready(function() { 
    console.log($('#locations-json').data('json')); 
    console.log(JSON.parse($('#locations-json').data('json'))); # tried parseJSON 
    $('.class-destination-from').change(function() { 
     $.when(get_destination_from_state(),function(res){ 
      //if (res=='city'){ 
      // 
      //}elif(res=='airport'){ 
      // pass 
      //}elif(res=='empty'){ 
      // pass 
      //} 
     }); 
    }) 
}); 

이 HTML의 일부입니다

Object {cities: "[1, 2, 3, 4]", airports: "[5, 6]"} VM1345:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1

콘솔 :

<div id="locations-json" data-json="{&quot;cities&quot;: &quot;[1, 2, 3, 4]&quot;, &quot;airports&quot;: &quot;[5, 6]&quot;}" style="display: none"></div> 

가 제대로 변환하는 방법을 알고 계십니까?

+1

JSON 개체에는 따옴표가있는 키가 있어야합니다. '{ "cities": "[1, 2, 3, 4]", "airports": "[5, 6]"}' – Frxstrem

+0

[ JSON] (http://stackoverflow.com/questions/11338774/serialize-form-data-to-json) – SAM

+0

@TJCrowder 질문의 맨 아래에 요소를 추가했습니다. –

답변

3

문제는 자주 발생하므로 data은 대부분의 사람들이 생각하는 것이 아닙니다. data이 아니고data-* 속성의 접근 자이며 그 이상이고 그보다 작습니다. 그것은 요소에 대한 jQuery의 내부 데이터 캐시를 관리합니다. 은 특성의 캐시를으로 초기화하지만 캐시의 데이터를 복제하고 데이터를 처리하며 결코 특성에 다시 쓰지 않습니다.

data은 당신이 읽고있는 내용이 JSON이고 자동으로 을 구문 분석합니다. 따라서 객체를 가져오고 파싱 할 필요가 없습니다. 그래서 data를 사용

:

var locations = $("#locations-json").data("json"); 
 
console.log(locations); 
 
console.log("There are " + locations.cities.length + " cities");
<div id="locations-json" data-json="{&quot;cities&quot;: &quot;[1, 2, 3, 4]&quot;, &quot;airports&quot;: &quot;[5, 6]&quot;}" style="display: none"></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

당신은 12 개 도시가 말한다 댓글에서 언급 한 바와 같이.

{"cities": [1, 2, 3, 4], "airports": [5, 6]} 

예 :

var locations = $("#locations-json").data("json"); 
 
console.log(locations); 
 
console.log("There are " + locations.cities.length + " cities");
<div id="locations-json" data-json="{&quot;cities&quot;: [1, 2, 3, 4], &quot;airports&quot;: [5, 6]}" style="display: none"></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

당신은 아마가되도록 JSON을 의미

{"cities": "[1, 2, 3, 4]", "airports": "[5, 6]"} 

다음 JSON은 cities (그리고 airports)는 문자열 값을 제공하기 때문이다 당신이 data의 다양한 기능을 필요로하지 않는 1,363,210


하지만, 단지 자신을 attr를 사용하여 구문 분석 :

var locations = JSON.parse($("#locations-json").attr("data-json")); 
 
console.log(locations); 
 
console.log("There are " + locations.cities.length + " cities");
<div id="locations-json" data-json="{&quot;cities&quot;: [1, 2, 3, 4], &quot;airports&quot;: [5, 6]}" style="display: none"></div> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


참고 :

으로 this edit의 질문 이처럼 보이는 div이 유효합니다. :

<div id="locations-json" data-json="{&quot;cities&quot;: &quot;[1, 2, 3, 4]&quot;, &quot;airports&quot;: &quot;[5, 6]&quot;}" style="display: none"></div> 

그러나 you edited it again이 잘못되는, 다음과 같이합니다 : &quot;

<div id="locations-json" data-json="{"cities": "[1, 2, 3, 4]", "airports": "[5, 6]"}" style="display: none"></div> 

버전이 올바른지, 그것을 사용하십시오.

+0

JSON을 올바르게 구문 분석하는지 잘 모르겠지만이 영역에서 새로 작성되어 올바른 것일 수 있습니다. 내가 할 때 : $ ('# locations-json'). data ('json'). 올바른 도시 [1, 2, 3, 4]. 그러나 첫 번째 도시를 얻으려고 할 때 - 그래서 1 - 배열은 문자열이라고 생각하는 것처럼 [ ""를 반환합니다. –

+0

@ MilanoSlesarik : 질문에 대한 제 의견을 보자. 요소의'json' 속성이 올바르게 출력되었는지 확인해야한다. 나는 또한 위의 대답의 끝 부분에 대한 메모를 추가했습니다. –

+0

어쩌면 나는 어떤 것을 얻지 못할 것이지만, 여러분의 코드는 12 개 도시가 있다는 것을 반환하므로 값은 배열 /리스트가 아닌 문자열입니다. –

관련 문제