1

I have a Nodejs lambda function that needs to parse JSON sent to it from an external application. The JSON appears to be malformed and comes in as an object key like so:

 console.log(req.body)

results in:

{ '{"id":"258830096441","time":10}': '' }

What I need is the id and id number, but I am stumped as to how I could parse this.

HodgePodge
  • 15
  • 1
  • 6

2 Answers2

2

If req.body is an object, you can get the first key of the array returned by Object.keys() and then JSON.parse() that key to finally get the id. Like shown on next example:

const obj = { '{"id":"258830096441","time":10}': '' };

let id = JSON.parse(Object.keys(obj)[0]).id;

console.log(id, typeof id); // As string.
console.log(+id, typeof +id); // As number, in case you need the id as number.
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Shidersz
  • 16,846
  • 2
  • 23
  • 48
0

You can parse out the key by doing Object.keys(req.body)[0], which will give you a string, and then you can convert this string to an object by calling JSON.parse on it. The end result would look something like:

let myReqBody = JSON.parse(Object.keys(req.body)[0])

Then you can access the attributes of myReqBody like you normally would:

myReqBody.id
Alex Dovzhanyn
  • 1,028
  • 6
  • 14