javascript 如何在javascript中将json格式的字符串转换为json数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7611845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:41:37  来源:igfitidea点击:

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

javascriptjquery

提问by Vincent

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

我正在使用 $.post() 方法来检索一个 json 格式的字符串,它看起来像这样:

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

In the success callback function of $.post(), I would like to loop the values of this json formatted string but I can't figure out how to do it.

在 $.post() 的成功回调函数中,我想循环这个 json 格式字符串的值,但我不知道该怎么做。

  // 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

当我这样做时value = 10, value = 11, value = 12,我得到的不是在警告框中得到等,而是得到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

感谢您的帮助

回答by user113716

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

如果您没有'['']'字符,则您的字符串不是有效的 JSON 。

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

您可以将它们添加到 中,然后使用jQuery.parseJSON()[docs]方法解析它。

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

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

...但如果您从服务器发送正确的 JSON 数据会更好。

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

此外,您的 JSON 键必须用双引号括起来。

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

回答by Vivin Paliath

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:

您的查询未返回有效的 JSON。应该是[{"elementid":10},{"elementid":11},{"elementid":12},{"elementid":14},{"elementid":15}],不是{elementid:10},{elementid:11},{elementid:12},{elementid:14},{elementid:15}。有什么办法可以解决这个问题吗?否则,您将不得不这样做:

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).

但是,正确的做法是从服务器返回有效的 JSON(如果您对此有任何控制)。

回答by Bene

Use the "for in" statement. Such as:

使用“for in”语句。如:

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).

附言。Console.log() 在浏览器控制台中输出结果(当然,它在 IE 中不起作用)。

回答by Rene Pot

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

用于JSON.parse(data)将包含 JSON 对象的字符串放入变量中

回答by Richard Dalton

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:

试试这个,看起来你正在传递一个数组(除了缺少周围的 []),如果你告诉 jquery 它是 json,它会为你正确解析它:

$.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