views:

50

answers:

2

I have a generic JSON structure I want to put in to a JavaScript object.

My JSON is like this

{
"rows": [
    {
        "items": [
            {
                "key": "foo1",
                "value": "bar1" 
            } ,
            {
                "key": "foo2",
                "value": "bar2" 
            } 
        ] 
    } 
] }

What is the easiest way to convert this in to a JS object like this:

Item.foo1 = 'bar1';
Item.foo2 = 'bar2';

I can use something like JSONPath But I thought maybe there is a simpler way to do this? using straight JavaScript?

+1  A: 

Something like

var Item = {};
var items = object.rows.items;
for (var i=0; i<items.length; i++) {
  Item[items[i].key] = items[i].value;
  }

?

rob
Too easy, thanks
Daveo
this will not work as the `rows` is an array.. to access the `items` you need to go through its index of 0..
Gaby
+1  A: 

Live at http://www.jsfiddle.net/QcLk8/2/

var json = {
 "rows": [
    {
        "items": [
            {
                "key": "foo1",
                "value": "bar1"
            } ,
            {
                "key": "foo2",
                "value": "bar2"
            }
        ]
    }
] }

 var items={}
 var jsonItems = json.rows[0].items;
 for(var idx=0;idx<jsonItems.length;idx++)
    {
      var item = jsonItems[idx];
      items[item.key] = item.value;
    }


 alert(items.foo1);
Gaby
Thank you for the complete working sample
Daveo