在JS中打印json数组[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我正在尝试使用PHP从JS浏览器控制台打印我的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']);

        }
      });
  });
}); 
javascript arrays json multidimensional-array
2个回答
1
投票

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

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

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


0
投票

您提供的JSON示例将解析为Object。你可以尝试类似的东西:

const data = JSON.parse(response);
const array = Object.keys(data).map(key => data[key]);
array.forEach(item => console.log(item.codigo_intervencao))

对于没有codigo_intervencao密钥的对象,您将获得未定义的内容。或者,您可以使用for..in迭代您的对象。

© www.soinside.com 2019 - 2024. All rights reserved.