javascript - JS中打印json数组

标签 javascript arrays json multidimensional-array

我正在尝试使用 JS 在浏览器控制台中打印来自 PHP 的 JSON 响应。 我在这里和其他网站上看到了很多帖子,但我做不到。

我有一个这样的 JSON

{"0":{"codigo_intervencao":"Apoio Emocional - 5270"},"1":{"tempo":"30"},"2":{"codigo_intervencao":"Apoio Emocional - 5270"},"3":{"tempo":"30"},"4":{"codigo_intervencao":"Apoio Emocional - 5270"},"5":{"tempo":"231518"},"6":{"codigo_intervencao":"Apoio Emocional - 5270"}}

我想在控制台中打印,例如,“codigo_intervencao”键的每个值,但我无法实现这一点。

我尝试过类似的事情:

$(document).ready(function() {

  $( "#target" ).click(function() {
    console.log("Select JS");
      $.ajax({
        type: "POST",
        url: "select.php",
        dataType: 'html',
        success: function(response) {
            console.log("Response:" + response); // Here it prints above json
            var array = $.parseJSON(response);
            var tempo = 0;
            var arrayLength = array.length;

            for (var i = 0; i < arrayLength; i++) {
              console.log(array[i]['codigo_intervencao']);

        }
      });
  });
}); 

最佳答案

您有一个 JSON 对象,而不是数组。

var elements = $.parseJSON(response)
for (element in elements){
    console.log(elements[element]['codigo_intervencao'])
}

迭代 JSON 并获取所需的元素。

关于javascript - JS中打印json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49040397/

相关文章:

javascript - 使我的函数可重用

c++ - 要求用户输入他/她的名字,然后反转给定的名字并将其显示在屏幕上。使用字符数组

javascript - 如何通过js打印数组中的所有case元素

Swift 中的 JSON 和 Node 如何实现 GET 请求中类别的过滤器

json - 如何将日期插入ArangoDB?

javascript - 使用jquery在bootstrap卡中显示json数据

javascript - 当我尝试访问元素的数据时,为什么 jQuery 返回 undefined?

javascript - 将参数从 anchor 标记发送到 struts2 操作

javascript - 是否可以在通过表单上传之前预览本地镜像?

javascript - SummerNote Rich Editor文本区域高度变为零