Demyan Borya
Demyan Borya

Reputation: 121

'Unable to get value from JSON object in node js

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

Upvotes: 2

Views: 1531

Answers (2)

Ivan Vasiljevic
Ivan Vasiljevic

Reputation: 5718

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

Upvotes: 1

skAstro
skAstro

Reputation: 374

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

Upvotes: 1

Related Questions