Javascript 读取一个简单的JSON数组

Javascript 读取一个简单的JSON数组,javascript,Javascript,我正在尝试发送一个简单的数组,但它不起作用。我只想同时发送所有数组并读取containerName和containerStatus 我的第一个console.log输出这个 {“containerName”:“123”,“containerStatus”:“最多2小时”}{“containerName”:“ingesdev”,“containerStatus”:“最多2小时”} 爪哇 VM362:1未捕获的语法错误:JSON中位置处的意外标记{ 54 在JSON.parse()处 在Object

我正在尝试发送一个简单的数组,但它不起作用。我只想同时发送所有数组并读取containerName和containerStatus

我的第一个console.log输出这个

{“containerName”:“123”,“containerStatus”:“最多2小时”}{“containerName”:“ingesdev”,“containerStatus”:“最多2小时”}

爪哇

VM362:1未捕获的语法错误:JSON中位置处的意外标记{ 54 在JSON.parse()处 在Object.success(dashboard.js:10) at i(jquery.min.js:2) 在Object.fireWith[as resolveWith](jquery.min.js:2) 在A(jquery.min.js:4) 在XMLHttpRequest上。(jquery.min.js:4)

  • 在将对象放入带有循环的数组中之后,应该在Java端返回一次JSONArray中的对象

  • URL是否正确?可能是
    /Containers
    http://localhost:8080/containers
    ?我的意思是,数据的路径是什么

  • 解析数据后,您可以通过索引访问元素:
    containers[0]。fieldName


  • 您没有将有效的JSON返回给客户端。顶层不能有多个连续对象。顶层应该有一个包含这些对象的数组

    服务器端:

    JSONArray jsonArray = new JSONAarray();
    
    for (Container container:runningContainers) {
      JSONObject obj = new JSONObject();
      obj.put("containerName", container.getNames()[0].replace("/",""));
      obj.put("containerStatus",container.getStatus());
      jsonArray.put(obj);
    }
    response.getWriter().write(jsonArray.toString());
    
    客户端:

    $.ajax({
        type: 'post',
        url: 'Containers',
        success: function (result) {
          JSON.parse(result).forEach(function(container) {
            console.log(container.containerName);
          });
        },
        error: function() {
    
        }
    });
    

    您没有向客户端返回有效的JSON。在顶层不能有多个连续的对象。在顶层应该有一个包含这些对象的数组。或者只返回一个对象。我想同时返回所有对象,但在使用时这些对象都过多了。请放置,以便我只能看到最后一个。正如我所说的,哟你必须创建一个对象数组。请检查我的编辑。
    JSONArray jsonArray = new JSONAarray();
    
    for (Container container:runningContainers) {
      JSONObject obj = new JSONObject();
      obj.put("containerName", container.getNames()[0].replace("/",""));
      obj.put("containerStatus",container.getStatus());
      jsonArray.put(obj);
    }
    response.getWriter().write(jsonArray.toString());
    
    $.ajax({
        type: 'post',
        url: 'Containers',
        success: function (result) {
          JSON.parse(result).forEach(function(container) {
            console.log(container.containerName);
          });
        },
        error: function() {
    
        }
    });