简体   繁体   中英

Using JSON.stringify and can't access the JSON array

I am using php and using json_encode() function I returned/echoed JSON array. I was using jquery ajax and successfully retrieved this data:

[{"id":"1132","city":"Manila Central Post Office","province":"Manila"}]

I use this code on my Javascript btw:

var val = jQuery.parseJSON(JSON.stringify(result));

and when I tried to accessed the data on the array like:

console.info(val.city); // results to undefine

It gives me 'undefined' result. I tried doing For in loop still doesn't work. Maybe I'm doing something wrong, any help would be great. THANKS

Ajax code:

$.ajax({
    type: 'POST',
    url: path,
    cache: false,
    data: postData,
    success: function (result) {
        var val = jQuery.parseJSON(JSON.stringify(result, false, replacer));
        var val2 = jQuery.parseJSON(val);
        console.info(val2);
        console.info(val2.id);
    },
    error: function (e) {
        $("#sys_msg").html(e);
        $("#myModal").modal({
            show: true,
            backdrop: false,
            keyboard: true
        });
    }
});

val is an array. You need to specify index like below.

 var result = [{ "id": "1132", "city": "Manila Central Post Office", "province": "Manila" }]; var val = jQuery.parseJSON(JSON.stringify(result)); alert(val[0].city); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Here val is an array of objects, so you cannot access the city value directly by calling val.city . If the data being returned is already encoded by using json_encode() , then you simply need to use $.parseJSON(data) . The following code snippet shows how to do this-

 var temp = '[{"id":"1132","city": "Manila Central Post Office", "province":"Manila"},{"id":"1133","city": "Another Test Post Office", "province":"Test"}]'; //Defined temp as string since the data response returned from the server should also be a json encoded string. var val = $.parseJSON(temp); $.each(val, function(index, item) { var city = item.city; $('.container').append('City: '+city+'<br/>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <div class="container"></div> 

See, the issue can be easily resolved by dataType:"json" . If you don't have this attached in your ajax code then the returned response will be a json string and in this case only you have to parse it with jQuery.parseJSON() or JSON.parse() .

So, you can add the dataType to the ajax or instead just only parse it.

success: function(result){
  var val = jQuery.parseJSON(result); // or JSON.parse(result);
  console.info(val[0].city);
},

With dataType :

$.ajax({
  type: 'POST',
  url: path,
  cache: false,
  data: postData,
  dataType: 'json', //<-----add this here
  success: function(result) {
    for (o in result) { // <----and just use this way
      console.info(o.city);
    }
  },
  error: function(e) {
    $("#sys_msg").html(e);
    $("#myModal").modal({
      show: true,
      backdrop: false,
      keyboard: true
    });
  }
});

You don't have to stringify it then parse it to JSON again. You can just add dataType: "json" in your AJAX.

$.ajax({
    type: 'POST',
    url: path,
    cache: false,
    data: postData,
    dataType: "json",

    success: function (result) {

        console.info(result);
        console.info(result.id);
    },
    error: function (e) {
        $("#sys_msg").html(JSON.stringify(e));
        $("#myModal").modal({
            show: true,
            backdrop: false,
            keyboard: true
        });
    }
});

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