如何在javascript中从JSON获取值

时间:2012-05-21 12:21:11

标签: javascript json

如何从javascript中获取JSON中的值是我的代码

var obj={"0.5":0.009333, "0.21":0.048667,"0.31":0.070667};
    var value =0.21;
    var p=0;
    for(i=0; i<= obj.length ;i++){
    if(value== obj[i]){                         
           p = obj[i];                   //here i want p=0.048667
           console.log("psr is :"+p);
        }
    }

2 个答案:

答案 0 :(得分:1)

呃...不只是obj[value]这个伎俩? )

答案 1 :(得分:0)

Javascript不支持

obj.length。您将不得不使用

循环它
for(var index in object) {
    var p = object[index];
    console.log(p);
}

但当然如果你已经知道了你的钥匙,那么

console.log(object[key]);

是要走的路。完整的代码变为

var obj = {"0.5":0.009333, "0.21":0.048667,"0.31":0.070667};
var value = "0.21";
var p = obj[value];
console.log(p);