Search code examples
jqueryjsonadobe-edge

Reading JSON with $.getJSON


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
  });
}

Solution

  • 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.