2

I have a jsp file that returns a json object using the following code:

    JSONObject object = new JSONObject();

    object.put("name","domain");
    object.put("email","domain.com");

    response.setContentType("application/json");
    response.getWriter().write(object.toString());

The output is: {"name":"domain","email":"domain.com"}

I trying to get the values from this JSON using following code in node.js:

        var endpoint = // contains the address of the above jsp file;

        var body = ""
        http.get(endpoint, (response) => {
          response.on('data', (chunk) => { body += chunk })
          response.on('end', () => {
            console.log("Body: "+body);
            console.log("Body name: "+body.name);
          })
        })

In the above snippet I get following output for console.log -

Body: {"name":"domain","email":"domain.com"}

Body name: undefined

I don't know why "body.name" is not working. Could any body please help in getting the values from the json object. Since, body itself is json object so I don't need to do JSON.parse

2 Answers 2

1

Try this. You have to parse the JSON string to assign it to a js object.

    var endpoint = // contains the address of the above jsp file;

    var body = {}
    http.get(endpoint, (response) => {
      response.on('data', (chunk) => { body = JSON.parse(chunk) })
      response.on('end', () => {
        console.log("Body: "+body);
        console.log("Body name: "+body.name);
      })
    })
Sign up to request clarification or add additional context in comments.

Comments

1

body object is string. Because of that when you try to write it in console:

console.log("Body: "+body); 

You get this:

Body: {"name":"domain","email":"domain.com"}

But since body is string you cannot get its property name. String doesn't have proerty name. You should firstly parse string to JSON

    var endpoint = // contains the address of the above jsp file;

    var body = ""
    http.get(endpoint, (response) => {
      response.on('data', (chunk) => { body += chunk })
      response.on('end', () => {
        console.log("Body: "+ body);
        var parsedBody = JSON.parse(body);
        console.log("Body name: "+ parsedBody .name);
      })
    })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.