0
votes

I'm trying to send a simple array but it's not working. I just want to send all the array at the same time and read containerName and containerStatus.

My first console.log outputs this.

{"containerName":"123","containerStatus":"Up 2 hours"}{"containerName":"ingesdev","containerStatus":"Up 2 hours"}

Java

 List<Container> runningContainers = dockerClient.listContainersCmd()
                        .exec();

                JSONObject jsonContainer = new JSONObject();

                for (Container container:runningContainers) {
                    jsonContainer.put("containerName", container.getNames()[0].replace("/",""));
                    jsonContainer.put("containerStatus",container.getStatus());
                    response.getWriter().write(jsonContainer.toString());
                }

JavaScript

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

    },
    error: function() {

    }
});

VM362:1 Uncaught SyntaxError: Unexpected token { in JSON at position 54 at JSON.parse () at Object.success (dashboard.js:10) at i (jquery.min.js:2) at Object.fireWith [as resolveWith] (jquery.min.js:2) at A (jquery.min.js:4) at XMLHttpRequest. (jquery.min.js:4)

2
You are not returning valid JSON to the client. You cannot have multiple consecutive objects at the top level. You should have an array at the top level that contains the objects. Or return only a single object.Felix Kling
I wanted to return all the objects in the same time but they are overwrriting when i use .put so I can only see the last one.asdasd
As I said, you have to create an array of objects.Felix Kling
check my edit please.asdasd

2 Answers

1
votes

You are not returning valid JSON to the client. You cannot have multiple consecutive objects at the top level. You should have an array at the top level that contains the objects.

Server side:

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());

Client side:

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

    }
});
0
votes
  1. You should return once on your Java side the objects inside an JSONArray, after putting the objects inside the array with loop.

  2. Is the URL correct? Maybe /Containers or http://localhost:8080/containers? so, I mean what is the path to data?

  3. After parsing the data, you access your elements through index: containers[0].fieldName