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?
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);
Something like
var Item = {};
var items = object.rows.items;
for (var i=0; i<items.length; i++) {
Item[items[i].key] = items[i].value;
}
?
精彩评论