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
  • 103,943
  • 14
  • 161
  • 157
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
  • 188,624
  • 52
  • 326
  • 405
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,818
  • 2
  • 22
  • 45
Alok Agarwal
  • 3,071
  • 3
  • 23
  • 33