0

For a college assignment I have to read JSON data into an Adobe Edge project. In the JSON below you will see I made an array of colors. A function setElementsColor(color) has to look up the correct object in the Colors array of the json file. So the argument color has to be equal the colorName of the object. I am not quite sure how to do this.

Here is the JSON:

{
    "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"
        }
    ]
}

The following function is used to read out the JSON-file.

function setElementsColor(color){
  $.getJSON('json/colors.json',function(data){
    //The JSON must be read out here
  });
}
Alexander
  • 23,432
  • 11
  • 63
  • 73
svdotbe
  • 168
  • 1
  • 3
  • 16
  • 1
    your json object seems to be valid on a linter. did you try a simple $.get('json/colors.json', function(data) { /*data.colors*/ }, 'json'); ? it could also come from the content-type header of the json file you request. It should be "application/json"... try to check this. – y_nk Jan 02 '13 at 17:22
  • Check the [API reference](http://api.jquery.com/jQuery.getJSON/). Your JSON is already decoded in `data`. – Álvaro González Jan 02 '13 at 17:26
  • @y_nk how do you change content-type header? – svdotbe Jan 02 '13 at 18:06

1 Answers1

0

I'd use $.grep.

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

I'd be easier if Colors were an Object instead of an Array.

Disclaimer: Untested.

Alexander
  • 23,432
  • 11
  • 63
  • 73
  • Thanks for the valuable answer. However, it seems the getJSON function doesn't work. – svdotbe Jan 02 '13 at 17:55
  • 1
    @SylvainVansteelandt, that's strange. Probably you can try `$.ajax` directly. Or, check [this previous answer of mine](http://stackoverflow.com/a/14047889/417685), it explains how to force a JSON data type in `$.ajax` – Alexander Jan 02 '13 at 18:19
  • Problem Solved, I ran the JSON in a validator and there was a comma after the last object. – svdotbe Jan 02 '13 at 18:29