views:

40

answers:

2

Hi,

I am a noob when it comes to json. The more I use it, I am starting to like it. I have a output that looks like this

[
    {
        "product": {
            "id": "6",
            "category": "Books",
            "created": "2010-04-13 15:15:18",
        },
        "availability": [
            {
                "country": "United Kingdom",
                "price": "$13.99",
            },
            {
                "country": "Germany",
                "price": "$13.99",
            }
        ]            
    }
]

Actually I have listed only one product, But output has many products listed. I want to loop through this json output and get all the product's category, countries where they are available and price using fbjs.

I appreciate any help.

Thanks.

A: 

Use json parsers. Check out parser for your language here.
And you current data format looks not according to json protocol.

{"products":[
  {
    "product": {
        "id": "6",
        "category": "Books",
        "created": "2010-04-13 15:15:18",
    },
    "availability": [
        {
            "country": "United Kingdom",
            "price": "$13.99",
        },
        {
            "country": "Germany",
            "price": "$13.99",
        }
    ]            
}]}
Zimbabao
@Zimbabao I valiated it, it says valid json.
Melanie W
+1  A: 

If your JSON is like this,

var products = [
    {
        "product": {
            "id": "6",
            "category": "Books",
            "created": "2010-04-13 15:15:18",
        },
        "availability": [
            {
                "country": "United Kingdom",
                "price": "$13.99",
            },
            {
                "country": "Germany",
                "price": "$13.99",
            }
        ]            
    },
    {
        "product": {
            "id": "7",
            "category": "Books",
            "created": "2010-04-13 15:15:18",
        },
        "availability": [
            {
                "country": "United Kingdom",
                "price": "$13.99",
            },
            {
                "country": "Germany",
                "price": "$13.99",
            }
        ]            
    }
]

You can iterate through:

for(var index = 0; index < products.length; index++) {
  alert(products[index].product.category);
}
Marimuthu Madasamy