Alon Shlider
Alon Shlider

Reputation: 1298

How to extract a parameter of JSON object that is full with escape characters - '\'

I have a serverless project running on Node JS that gets a respons to it with the following escape character - "\". Here is my object that I get as a response to me -

"{\"desc\":\"India next talent\",\"name\":\"אחלה ברווז\",\"uid\":\"-LnQwxh_QoYl4Qj_9M4B\"}"

So basiclly, as you can see, this is a JSON object with some wierd escape characters. The full object is called

reqBody.context.custom.miniContest

So what I need is the 'uid' parameters of the miniContest, but when trying to call it -

reqBody.context.custom.miniContest.uid

I get undefined. So my question is how can I extract the value of 'uid' successfully?

Upvotes: 1

Views: 68

Answers (1)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

It seems you're doing JSON.stringify() twice. You can avoid it if you've the access on the server side codebase.

Say, If you have this,

const config = {a: 1, b: 2}
console.log(JSON.stringify(JSON.stringify(config)))

then it will produce below response with extra \,

"{\"a\": 1, \"b\": 2}"

To extract the value of 'uid' successfully, You can use JSON.parse() to make it object before accessing it, Let's do it this way-

let json = "{\"desc\":\"India next talent\",\"name\":\"אחלה ברווז\",\"uid\":\"-LnQwxh_QoYl4Qj_9M4B\"}";

let result = JSON.parse(json);
console.log(result.uid);

Upvotes: 1

Related Questions