1

I am creating a list by fetching values from a JSON file. It is a nested JSON and the list items are- "Thriller","Fiction" which are basically keys for the next level. on click of the item I'm passing its name(i.e. Thriller/fiction) to another function... var val = thriller.

Now I need to fetch the value(i.e. "book" & bookname) corresponding to the passed key in this new function. I'm not able to do so using dot operator- data.library.val not working..

If anybody has worked on something similar..please help..

JSON:

{ "library": [

    {
        "Thriller": [
            { "book": "ABC" },
            { "book": "DEF" }
        ]
    },
    {
        "Fiction": [
            { "book": "GHI" },
            { "book": "JKL" }
        ]
    },]  }

Code snippet:

$.getJSON('resources/abc.json', function(data){

        var i = data.library;
        $("#menuList1").css('display','block');
        $(i).each(function(key, value){
            $.each(value, function(key, value){
                    console.log(key);
                    $("#menuList1").append('<a href="#" id="'+key+'" onClick="createSubMenu(id);">'+key+'</a>');
    });       
   });    });
tymeJV
  • 102,126
  • 13
  • 159
  • 155
Moo07
  • 11
  • 1
  • 2
  • Use variable names that do not clash with each other! Make them meaningful so you can read them and know what you are actually referencing. – epascarello Apr 29 '13 at 14:23

2 Answers2

1

Use data.library[key]

MDN Documentation

Explosion Pills
  • 183,406
  • 48
  • 308
  • 385
1

Your Json is not valid, this },] specially. A good version :

{
    "library": [{
        "Thriller": [{
            "book": "ABC"
        }, {
            "book": "DEF"
        }]
    }, {
        "Fiction": [{
            "book": "GHI"
        }, {
            "book": "JKL"
        }]
    }]
}

you can refer the website http://jsonlint.com for validating your json.

Blag
  • 5,593
  • 2
  • 19
  • 43
Alok Agarwal
  • 2,980
  • 3
  • 21
  • 32