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
Add a ment  | 

5 Answers 5

Reset to default 3

If 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