2013-01-02 3 views
0

대학 과제를 위해 JSON 데이터를 Adobe Edge 프로젝트로 읽어야합니다. 아래 JSON에서는 배열의 색상을 볼 수 있습니다. setElementsColor(color) 함수는 Colors json 파일의 배열에서 올바른 객체를 검색해야합니다. 따라서 인수 color은 객체의 colorName과 같아야합니다. 나는 이것을 어떻게하는지 잘 모르겠습니다.

{ 
    "Colors": [ 
     { 
      "colorName": "Black", 
      "imageName": "fridge_black.jpg", 
      "footerName": "black_footer.png", 
      "facebookLogo": "black_facebook.png", 
      "twitterLogo": "black_twitter.png", 
      "linkedinLogo": "black_linkedin.png" 
     }, 
     { 
      "colorName": "Blue", 
      "imageName": "fridge_blue.jpg", 
      "footerName": "blue_footer.png", 
      "facebookLogo": "blue_facebook.png", 
      "twitterLogo": "blue_twitter.png", 
      "linkedinLogo": "blue_linkedin.png" 
     } 
    ] 
} 

다음 함수는 JSON 파일을 읽는 데 사용됩니다 : 여기

는 JSON이다.

function setElementsColor(color){ 
    $.getJSON('json/colors.json',function(data){ 
    //The JSON must be read out here 
    }); 
} 
+1

json 개체가 linter에서 유효한 것으로 보입니다. 간단한 $ .get ('json/colors.json', function (data) {/*data.colors*/}, 'json')을 사용해 보았습니까? ? 당신이 요청한 json 파일의 content-type 헤더에서도 올 수 있습니다. 그것은 "application/json"이어야합니다 ... 이것을 확인하십시오. –

+0

[API 참조] (http://api.jquery.com/jQuery.getJSON/)을 확인하십시오. JSON은 이미 '데이터'로 디코딩됩니다. –

+0

@y_nk 콘텐츠 형식 헤더를 어떻게 변경합니까? –

답변

0

나는 $.grep을 사용합니다.

function setElementsColor(color){ 
    $.getJSON('json/colors.json',function(data){ 
    var obj = $.grep(data.Colors, function(color) { 
     return color.colorName === color; 
    }); 
    /* Use obj */ 
    }); 
} 

Colors이 배열 대신 Object 인 경우 더 쉬울 것입니다.

면책 조항 : 테스트되지 않음.

+0

귀중한 답변에 감사드립니다. 그러나 getJSON 함수가 작동하지 않는 것 같습니다. –

+1

@SylvainVansteelandt, 그건 이상합니다. 아마'$ .ajax'를 직접 사용해 볼 수 있습니다. 또는 [이전 답변] (http://stackoverflow.com/a/14047889/417685)에서'$ .ajax'에 JSON 데이터 유형을 강제하는 방법을 설명합니다. – Alexander

+0

문제가 해결되어 JSON을 유효성 검사기와 마지막 개체 뒤에 쉼표가있었습니다. –