2
I have a json string like 
{
"Msg1": "message 1",
"Msg2": "message 3",
"Msg3": "message 2"
}

我正在使用以下代码

  function GetMessages(msg) {
   $.getJSON("./jquery/sample.json", function (result) {
        $.each(result, function (key, val) {
            if (key == msg) {
                alert(val);
            }
        });
}

有没有其他方法可以检查我的键是否存在于结果数组中并在不使用 foreach 循环的情况下获取它的值?eval() 可以做点什么吗?

4

5 回答 5

3

如果您知道属性名称,则可以直接访问它,而无需遍历其属性:

var msg = 'Msg2';

$.getJSON('./jquery/sample.json', function (result) {
    alert(result[msg]);
});
于 2013-01-23T08:05:08.720 回答
3

使用in 运算符

function GetMessages(msg) {
   $.getJSON("./jquery/sample.json", function (result) {
       if (msg in result) {
           alert(result[msg]);
       }
    }
}
于 2013-01-23T08:11:52.967 回答
0

检查它是否存在

result["your_key"] !== undefined // as undefined is not a valid value this workes always
result.your_key !== undefined // works too but only if there aren't any special chars in it

并且获取值是相同的,但没有比较操作。

于 2013-01-23T08:15:47.773 回答
0

当你使用 $.getJSON 时,你会得到一个内部对象,所以你可以使用多种方式来判断:

if(result['msg']){
    alert(result['msg']);
}
//
if(typeof result['msg']!=='undefined'){
    ...
} 
//
if('msg' in result){
    ...
}
//
if(result.hasOwnProperty('msg')){
    ...
}

仔细考虑随时使用 eval(),它是 eve.sorry,我的英语很差,我希望它对你有用。thx!

于 2013-01-23T08:29:44.070 回答
-1

您可以使用 parseJSON

var obj = $.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

http://api.jquery.com/jQuery.parseJSON/

于 2013-01-23T08:10:09.987 回答