admin管理员组文章数量:1391987
I have a json string like
{
"Msg1": "message 1",
"Msg2": "message 3",
"Msg3": "message 2"
}
I am using the folowing code
function GetMessages(msg) {
$.getJSON("./jquery/sample.json", function (result) {
$.each(result, function (key, val) {
if (key == msg) {
alert(val);
}
});
}
Is there any other way to check if my key exists in the result array & get its value without using a foreach loop ? Can eval() do something ?
I have a json string like
{
"Msg1": "message 1",
"Msg2": "message 3",
"Msg3": "message 2"
}
I am using the folowing code
function GetMessages(msg) {
$.getJSON("./jquery/sample.json", function (result) {
$.each(result, function (key, val) {
if (key == msg) {
alert(val);
}
});
}
Is there any other way to check if my key exists in the result array & get its value without using a foreach loop ? Can eval() do something ?
Share Improve this question asked Jan 23, 2013 at 8:03 user339160user339160 1- have you tried result[msg] ? – Zathrus Writer Commented Jan 23, 2013 at 8:05
5 Answers
Reset to default 3If you know the property name you could access it directly and you don't need to be looping through its properties:
var msg = 'Msg2';
$.getJSON('./jquery/sample.json', function (result) {
alert(result[msg]);
});
Use the in
operator.
function GetMessages(msg) {
$.getJSON("./jquery/sample.json", function (result) {
if (msg in result) {
alert(result[msg]);
}
}
}
To check if it exists
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
And getting the value is the same but without the parison operation.
when you use $.getJSON,you get an interal object,so you can use so many ways to judge:
if(result['msg']){
alert(result['msg']);
}
//
if(typeof result['msg']!=='undefined'){
...
}
//
if('msg' in result){
...
}
//
if(result.hasOwnProperty('msg')){
...
}
think carefully to use eval() anytime,it's eve.sorry,my english is poor,i hope it's useful for you.thx!
You can use parseJSON
var obj = $.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
http://api.jquery./jQuery.parseJSON/
本文标签: javascriptGet Value from json with jQuery without using foreach loopStack Overflow
版权声明:本文标题:javascript - Get Value from json with jQuery without using foreach loop - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744721912a2621743.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论