简体   繁体   中英

Get Value from json with jQuery without using foreach loop

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 ?

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 comparison 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.com/jQuery.parseJSON/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM