Search code examples
javascriptjsonnode.jsapilinkedin-api

Parse LinkedIn API response body to JSON


This is driving me nuts and I'm hoping someone has encountered this & come up with a clean, elegant solution. When making a JSON request to the LinkedIn REST Api, the body comes back as a string with new-line characters. When I parse the string to JSON with JSON.parse it appears to create a JSON Object, but I can't access the values with dot notation using their relative keys. I have tried escaping the new line characters, a combination of JSON.stringify then parsing, etc. I cannot get this to work and it's obnoxious, though I'm sure there's a simple solution I'm overlooking. Here's the response from the LinkedIn API:

{"statusCode":200,"body":"{\n \"numConnections\": 152,\n \"numConnectionsCapped\": false\n}","headers":{"server":"Apache-Coyote/1.1","x-li-request-id":"myid","vary":"*","x-li-format":"json","content-type":"application/json;charset=UTF-8","date":"Tue, 10 Jan 2017 00:08:01 GMT","x-li-fabric":"prod-ltx1","transfer-encoding":"chunked","x-li-pop":"prod-ltx1","set-cookie":["lidc=\"b=TB70:g=489:u=129:i=1484006881:t=1484082637:s=AQG3LuLPqWuZiIoHGf2NqD8O7mRfdA4q\"; Expires=Tue, 10 Jan 2017 21:10:37 GMT; domain=.linkedin.com; Path=/"],"x-li-uuid":"53NCd2VAmBSAAWKrrSoAAA=="},"request":{"uri":{"protocol":"https:","slashes":true,"auth":null,"host":"api.linkedin.com","port":443,"hostname":"api.linkedin.com","hash":null,"search":"?format=json","query":"format=json","pathname":"/v1/people/id=myid:(num-connections,num-connections-capped)","path":"/v1/people/id=myid:(num-connections,num-connections-capped)?format=json","href":"https://api.linkedin.com/v1/people/id=myid:(num-connections,num-connections-capped)?format=json"},"method":"GET","headers":{"authorization":"Bearer mytoken"}}}

I'm trying to access the value with key "numConnections" but just can't get to the value.

Using JSON.parse(response.body) gets me this result:

{"numConnections":152,"numConnectionsCapped":false}

however I still cannot access the values associated with each key using

myObj.numConnections or any of the other notation I've tried. How can I get a valid JSON object out of this in NodeJS?


Solution

  • The result of parsing response.body is an object - on which you can use dot notation or bracket notation to access the values:

    var parsedBody = JSON.parse(response.body);
    parsedBody.numConnections //152
    parsedBody['numConnections'] //152