开发者

How to convert a json formatted string into a json array in javascript

I am using the $.post() method to retrieve a json formatted string which looks like this:

{elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}

In the success callback functio开发者_高级运维n of $.post(), I would like to loop the values of this json formatted string but I can't figure out how to do it.

  // data returns {elementid:10},{elementid:11},{elementid:12},{elementid:14}, etc.

  $.post('form.php',

        {'postvalues' : input_ids},

        function(data){

              var elements = Array();

              elements = [data];

              for(var i=0; i<elements.length; i++) {
                    var value = elements[i]['elementid'];
                    alert('value = '+value);
              }
  });

When I do this, instead of getting value = 10, value = 11, value = 12, etc. in the alert box, I get value = undefined

What must I change in the format of the variable 'data' so that it will be interpreted as array values and not a string?

thanks for your help


Your string isn't valid JSON if you don't have the '[' and ']' characters.

You can add those in , then parse it using the jQuery.parseJSON()[docs] method.

elements = jQuery.parseJSON( '[' + data + ']' );

...but it would be better if you sent correct JSON data from the server.

Also, your JSON keys must be wrapped in double quotes.

{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}


Your query isn't returning valid JSON. It should be [{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}] and not {elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}. Is there any way you can fix that? Otherwise, you will have to do this:

elements = jQuery.parseJSON("[" + data + "]");

The right thing to do, however, is to return valid JSON from the server (if you have any control over that).


use JSON.parse(data) to put a string which contains a JSON object in a variable


Try this, it looks like you are getting passed an array (apart from the missing surrounding []), and if you tell jquery that it's json it'll parse it for you properly:

$.post('form.php', {'postvalues' : input_ids}, function(data){              
    for(var i=0; i<data.length; i++) {
        var value = data[i]['elementid'];
        alert('value = '+value);
    }
}, 'json'); // telling it that the content received is json


Use the "for in" statement. Such as:

for (var x in data) {
    console.log(data[x]['elementid']);
}

I tested it and it perfectly worked! Hope this helps.

Ps. Console.log() output the result in the browser console (so it won't work in IE, of course).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜