JS遍历Json字符串中键值对先转成JSON对象再遍历

JavaScript014

JS遍历Json字符串中键值对先转成JSON对象再遍历,第1张

1、将Json字符串转换成JSON对象

var

t='{"firstName":

"cyra",

"lastName":

"richardson"}'

var

obj

=

eval('('

+

t

+

')')

2、遍历读取键值对

for(var

str

in

obj){

alert(str+'='+obj[str])

}

楼上的程序写错了,而且你的json字符串本身也错了吧?应该是这样的吧?

var s = {"val":[{"month":1,"num":235654},{"month":2,"num":1234321},

{"month":3,"num":948546},{"month":4,"num":987461},

{"month":5,"num":987654},{"month":6,"num":8746113},

{"month":7,"num":6481567},{"month":8,"num":9874324},

{"month":9,"num":6547214},{"month":10,"num":8541354},

{"month":11,"num":559563},{"month":12,"num":756424}]}

然后这样

var json = eval('('+s+')')

json = json.val

var arr = []

for(var i=0i<json.lengthi++)

arr[json[i].month] = json[i].num

然后arr就是你想要的数组

var str = '{"stuno":"0"}'

eval('var json = ' + str)

// var json = eval('('+str+')')

alert(json.stuno)//直接取值 结果0

for(var name in json){

alert(name )//name 结果 stuno

alert(json[name])//value 结果 0 和上面直接去是一样的

}

或者你的要求:

var key = 'stuno'

alert(json[key])//结果 0 和上面也一样

要采纳哦~