如何在 jQuery 中解析 JSON 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1607937/
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-08-26 11:49:09  来源:igfitidea点击:

How to parse JSON array in jQuery?

jqueryarraysjsoneach

提问by user97410

EDITI checked the jQuery documentation and using $.ajax with the json datatype specified returns an evaluated javascript object, so eval() isn't the answer here. I knew that anyway, since I am able to parse single JSON objects, just not arrays. The problem is the $.each-ing my way through them :)

编辑我检查了 jQuery 文档并使用 $.ajax 和指定的 json 数据类型返回一个评估的 javascript 对象,所以 eval() 不是这里的答案。我知道无论如何,因为我能够解析单个 JSON 对象,而不是数组。问题是 $.each-ing 我通过它们的方式:)

I have followed the syntax for parsing a JSON array in jQuery to the letter, but it doesn't work for some reason. I am fetching the array using $.ajax, have specified the correct datatype, and in Firebug can see that the response from my PHP script is []. Yet when I try to use $.each to iterate through the array, all I get is undefined values when I try to console.log various parts of the array. Here is where my php script makes and encodes the array:

我遵循了在 jQuery 中解析 JSON 数组的语法到字母,但由于某种原因它不起作用。我正在使用 $.ajax 获取数组,指定了正确的数据类型,并且在 Firebug 中可以看到来自我的 PHP 脚本的响应是 []。然而,当我尝试使用 $.each 遍历数组时,当我尝试 console.log 数组的各个部分时,我得到的只是未定义的值。这是我的 php 脚本制作和编码数组的地方:

if(mysqli_num_rows($new_res) > 0) {
$messages = array();

while($message_data = mysqli_fetch_assoc($query_res)) {
  $message = array(
    'poster' => $message_data['poster'],
    'message' => $message_data['message'],
    'time' => $message_data['time']
  );

  $messages[] = $message;
}

echo json_encode($messages);
} else if(mysqli_num_rows($new_res) == 0) {
$message = array(
  'poster' => '',
  'message' => 'No messages!',
  'time' => 1
);

echo json_encode($message);
}

And here is my attempt to parse it:

这是我解析它的尝试:

   var logged_in = '<?php echo $logged_in; ?>';
   var poster = '<?php echo $_SESSION["poster"];?>';
     $.ajax({
     url: 'do_chat.php5',
     type: 'post',
     data: ({'poster':poster,'logged_in':logged_in}),
     dataType: 'json',
     success: function(data) {
         $.each(data, function(messageIndex, message) {
                    console.log(parseInt($('#chatWindow :last-child > span').html())+' '+message['time']);
       if((parseInt(message['time']) > parseInt($('#chatWindow :last-child > span').html()))) {
     $('#chatWindow').append('<div class="poster">'+message['poster']+'</div><div class="message"><span>'+message['time']+'</span>'+message['message']+'</div>');
       }
       });
     }
     });

Without the $.each function I am able to successfully parse single JSON objects, but not an array. This is my first outing with JSON and $.each, and I'm pretty new to jQuery, so go easy if my code has ugly bits!

如果没有 $.each 函数,我可以成功解析单个 JSON 对象,但不能解析数组。这是我第一次使用 JSON 和 $.each,而且我对 jQuery 还很陌生,所以如果我的代码有难看的部分,那就放轻松吧!

回答by Cesar

No, with evalis not safe, you can use JSON parser that is much safer: var myObject = JSON.parse(data);For this use the lib https://github.com/douglascrockford/JSON-js

不,eval不安全,您可以使用更安全的 JSON 解析器:var myObject = JSON.parse(data);为此使用 lib https://github.com/douglascrockford/JSON-js

回答by Tocano

I know this is pretty long after your post, but wanted to post for others who might be experiencing this issue and stumble across this post as I did.

我知道这是在您发帖之后很久了,但我想为可能遇到此问题并像我一样偶然发现此帖子的其他人发帖。

It seems there's something about jquery's $.eachthat changes the nature of the elements in the array.

似乎有一些关于 jquery 的东西$.each改变了数组中元素的性质。

I wanted to do the following:

我想做以下事情:

$.getJSON('/ajax/get_messages.php', function(data) {

    /* data: 

    [{"title":"Failure","details":"Unsuccessful. Please try again.","type":"error"},
    {"title":"Information Message","details":"A basic informational message - Please be aware","type":"info"}]

    */

    console.log ("Data0Title: " + data[0].title);
    // prints "Data0Title: Failure"

    console.log ("Data0Type: " + data[0].type);
    // prints "Data0Type: error"

    console.log ("Data0Details: " + data[0].details);
    // prints "Data0Details: Unsuccessful. Please try again"


    /* Loop through data array and print messages to console */

});

To accomplish the loop, I first tried using a jquery $.eachto loop through the data array. However, as the OP notes, this doesn't work right:

为了完成循环,我首先尝试使用 jquery$.each循环遍历数据数组。但是,正如 OP 所指出的,这行不通:

$.each(data, function(nextMsg) {    
    console.log (nextMsg.title + " (" + nextMsg.type + "): " + nextMsg.details);
    // prints 
    // "undefined (undefined): undefined
    // "undefined (undefined): undefined
});

This didn't exactly make sense since I am able to access the data[0]elements when using a numeric key on the data array. So since using a numerical index worked, I tried (successfully) replacing the $.eachblock with a for loop:

这并不完全有意义,因为data[0]在数据数组上使用数字键时我能够访问元素。因此,由于使用数字索引有效,我尝试(成功)用$.eachfor 循环替换块:

var i=0;
for (i=0;i<data.length;i++){
    console.log (data[i].title + " (" + data[i].type + "): " + data[i].details);
    // prints
    // "Failure (error): Unsuccessful. Please try again"
    // "Information Message (info): A basic informational message - Please be aware"
}

So I don't know the underlying problem, a basic, old fashioned javascript for loop seems to be a functional alternative to jquery's $.each

所以我不知道潜在的问题,一个基本的、老式的 javascript for 循环似乎是 jquery 的功能替代 $.each

回答by Tocano

jQuery.parseJSON- new in jQuery 1.4.1

jQuery.parseJSON- jQuery 1.4.1 中的新内容

回答by Rammi Gill

I am trying to parse JSON data returned from an ajax call, and the following is working for me:

我正在尝试解析从 ajax 调用返回的 JSON 数据,以下内容对我有用:

Sample PHP code

示例 PHP 代码

$portfolio_array= Array('desc'=>'This is test description1','item1'=>'1.jpg','item2'=>'2.jpg');

echo json_encode($portfolio_array);

And in the .js, i am parsing like this:

在 .js 中,我是这样解析的:

var req=$.post("json.php", { id: "" + id + ""},
function(data) {
    data=$.parseJSON(data);
    alert(data.desc);
    $.each(data, function(i,item){
    alert(item);
    });
})
.success(function(){})
.error(function(){alert('There was problem loading portfolio details.');})
.complete(function(){});

If you have multidimensional array like below

如果您有如下所示的多维数组

$portfolio_array= Array('desc'=>'This is test description 1','items'=> array('item1'=>'1.jpg','item2'=>'2.jpg'));
echo json_encode($portfolio_array);

Then the code below should work:

那么下面的代码应该可以工作:

var req=$.post("json.php", { id: "" + id + 
    function(data) {
    data=$.parseJSON(data);
    alert(data.desc);
    $.each(data.items, function(i,item){
    alert(item);
    });
})
.success(function(){})
.error(function(){alert('There was problem loading portfolio details.');})
.complete(function(){});

Please note the sub array key here is items, and suppose if you have xyzthen in place of data.itemsuse data.xyz

请注意这里的子数组键是 items,假设你有xyz那么代替data.items使用data.xyz

回答by andrew.helgeland

Using .NET 3.5 FIX

使用 .NET 3.5修复

All of you are slightly wrong, but the combination of all of your efforts has paid off!

大家都错了,但是大家的努力得到了回报!

Instead of eval('([' + jsonData + '])'); do

而不是 eval('([' + jsonData + '])'); 做

success: function(msg){
var data = eval(msg.d);
var i=0;
for(i=0;i<data.length;i++){
    data[i].parametername /// do whatever you want here.
};

I don't know anything about the whole "don't use eval," but what I do know is that by doing the '([' + msg + '])' you are nesting those objects deeper, instead of up a level.

我对整个“不要使用 eval”一无所知,但我所知道的是,通过执行 '([' + msg + '])',您将这些对象嵌套得更深,而不是上一层.

回答by Victor

Careful with the eval, the JSON specs http://json.org/js.htmlrecommend something like

小心 eval,JSON 规范http://json.org/js.html推荐类似的东西

var myObject = eval('(' + myJSONtext + ')');

And there may be some more gotchas. There is a plugin for jQuery that will take care of it, i guess:

而且可能还有一些问题。有一个 jQuery 插件可以处理它,我想:

http://code.google.com/p/jquery-json/

http://code.google.com/p/jquery-json/

回答by meder omuraliev

Your datais a string of '[{}]'at that point in time, you can evalit like so:

data'[{}]'那个时间点的字符串,你可以eval这样:

function(data) {
    data = eval( '(' + data + ')' )
}

However this method is far from secure, this will be a bit more work but the best practice is to parse it with Crockford's JSON parser: https://github.com/douglascrockford/JSON-js

然而,这种方法远非安全,这将需要更多的工作,但最佳实践是使用 Crockford 的 JSON 解析器解析它:https: //github.com/douglascrockford/JSON-js

Another method would be $.getJSONand you'll need to set the dataTypeto json for a pure jQuery reliant method.

另一种方法是$.getJSON,您需要dataType将 json设置为纯 jQuery 依赖方法。

回答by meder omuraliev

You can use the Javascript eval() function to parse the JSON for you. See the JSON websitefor a better explanation, but you should be able to change your success function to...

您可以使用 Javascript eval() 函数为您解析 JSON。请参阅JSON 网站以获得更好的解释,但您应该能够将成功函数更改为...

var returnedObjects = eval(data);
var i = 0;
for (i = 0; i < returnedObjects.length; i++){
    console.log('Time: ' + returnedObjects[i].time);
}

...or something close.

...或接近的东西。

回答by Fermin

You can download a JSON parser from a link on the JSON.org websitewhich works great, you can also stringify you JSON to view the contents.

您可以从JSON.org 网站上的链接下载 JSON 解析器,该链接非常有效,您还可以将 JSON 字符串化以查看内容。

Also, if you're using EVAL and it's a JSON array then you'll need to use the following synrax:

此外,如果您使用的是 EVAL 并且它是一个 JSON 数组,那么您需要使用以下 Synrax:

eval('([' + jsonData + '])');

eval('([' + jsonData + '])');

回答by jamie

Do NOT eval. use a real parser, i.e., from json.org

不要评估。使用真正的解析器,即来自 json.org