Pergunta

Is it possible to have a key within a key in JSON and (if so) how would I access this in jQuery? This is my code:

{
    "product": [{
        "category": "Clothing",
        "items": [{
            "name": "Shirt",
            "price": "$4.99"
        }]
    }, {
        "category": "Food",
        "items": []
    }, {
        "category": "Electronics",
        "items": []
    }]
}

This is the jQuery I use to access the key-values:

$.getJSON('../JSON/cwdata.json', function (cwData) {
    $newData = cwData;        
    $.each($newData, function (key, value) {
        if (key === 'product[0].items[0]') {
            $('#product').append('<li>'+ value +'</li>')
    });
});

"#product" is an unordered list.

NOTE: I changed my JSON code to the code that was answered correctly by Salman A.

Foi útil?

Solução 2

Your JSON is invalid; arrays cannot have strings as keys. It needs to look like:

{
    "product": {
        "Clothing": {
            "Shirt": "$4.99"
        },
        "Food": {},
        "Electronics": {}
    }
}

Or may be like this:

{
    "product": [
        {
            "category": "Clothing",
            "items": [{
                "name": "Shirt",
                "price": "$4.99"
            }]
        }, {
            "category": "Food",
            "items": []
        }, {
            "category": "Electronics",
            "items": []
        }
    ]
}

To iterate over this data, use $.each a couple of levels deep:

$.each(cwData.product, function (i, product) {
    console.log(product.category + " (" + product.items.length + " items)");
    $.each(product.items, function (i, item) {
        console.log("\t" + item.name + ": " + item.price);
    });
});
// output:
//
// Clothing (1 items)
//     Shirt: $4.99
// Food (0 items)
// Electronics (0 items) 

Outras dicas

Yes it is possible. It should be something like this.

"availability": ["six", "five"],

   "connectivity": { "infrared": true,
   "gps" : true 
   }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top