Loop and get key/value pair for JSON array using jQuery

后端 未结 6 535
醉话见心
醉话见心 2020-11-29 23:31

I\'m looking to loop through a JSON array and display the key and value.

It should be a simplified version of the following post, but I don\'t seem to have the syn

相关标签:
6条回答
  • 2020-11-30 00:02
    var obj = $.parseJSON(result);
    for (var prop in obj) {
        alert(prop + " is " + obj[prop]);
    }
    
    0 讨论(0)
  • 2020-11-30 00:03

    Parse the JSON string and you can loop through the keys.

    var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';
    var data = JSON.parse(resultJSON);
    
    for (var key in data)
    {
        //console.log(key + ' : ' + data[key]);
        alert(key + ' --> ' + data[key]);
    }

    0 讨论(0)
  • 2020-11-30 00:05

    You can get the values directly in case of one array like this:

    var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';
    var result = $.parseJSON(resultJSON);
    result['FirstName']; // return 'John'
    result['LastName'];  // return ''Doe'
    result['Email']; // return 'johndoe@johndoe.com'
    result['Phone'];  // return '123'
    
    0 讨论(0)
  • The following should work for a JSON returned string. It will also work for an associative array of data.

    for (var key in data)
         alert(key + ' is ' + data[key]);
    
    0 讨论(0)
  • 2020-11-30 00:23

    You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

    var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe@johndoe.com","Phone":"123 dead drive"}';
    var result = $.parseJSON(resultJSON);
    $.each(result, function(k, v) {
        //display the key and value pair
        alert(k + ' is ' + v);
    });
    

    Live demo.

    0 讨论(0)
  • 2020-11-30 00:23

    The best and perfect solution for this issue:

    I tried the jQuery with the Ajax success responses, but it doesn't work so I invented my own and finally it works!

    Click here to see the full solution

    var rs = '{"test" : "Got it perfect!","message" : "Got it!"}';
    eval("var toObject = "+ rs + ";");
    alert(toObject.message);
    
    0 讨论(0)
提交回复
热议问题