Javascript 使用jQuery从json获取值,而不使用foreach循环
我正在使用以下代码Javascript 使用jQuery从json获取值,而不使用foreach循环,javascript,jquery,json,Javascript,Jquery,Json,我正在使用以下代码 I have a json string like { "Msg1": "message 1", "Msg2": "message 3", "Msg3": "message 2" } 是否有其他方法可以检查结果数组中是否存在我的键&在不使用foreach循环的情况下获取其值?eval()可以做些什么吗?如果您知道属性名称,您可以直接访问它,而不需要循环访问它的属性: function GetMessages(msg) { $.getJSON("./jquery/
I have a json string like
{
"Msg1": "message 1",
"Msg2": "message 3",
"Msg3": "message 2"
}
是否有其他方法可以检查结果数组中是否存在我的键&在不使用foreach循环的情况下获取其值?eval()可以做些什么吗?如果您知道属性名称,您可以直接访问它,而不需要循环访问它的属性:
function GetMessages(msg) {
$.getJSON("./jquery/sample.json", function (result) {
$.each(result, function (key, val) {
if (key == msg) {
alert(val);
}
});
}
您可以使用parseJSON
var msg = 'Msg2';
$.getJSON('./jquery/sample.json', function (result) {
alert(result[msg]);
});
使用中的
检查它是否存在
function GetMessages(msg) {
$.getJSON("./jquery/sample.json", function (result) {
if (msg in result) {
alert(result[msg]);
}
}
}
获取值是相同的,但没有比较操作。使用$.getJSON时,会得到一个内部对象,因此可以使用多种方法来判断:
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
任何时候都要仔细考虑使用eval(),现在是夏娃。对不起,我的英语很差,希望对你有用。谢谢 您是否尝试过result[msg]?当使用$.getJSON作为jquery自动将返回的数据转换为对象时,不需要使用parseJSON
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
if(result['msg']){
alert(result['msg']);
}
//
if(typeof result['msg']!=='undefined'){
...
}
//
if('msg' in result){
...
}
//
if(result.hasOwnProperty('msg')){
...
}