0

I'm trying to parse a json object that an application (AWS lambda) wrote in a log file, but this json has an stringify object nested. Something like that:

input = '{"object":"{\"base\":\"brn\",\"scope\":\"all\",\"channel\":\"sve\",\"service\":\"getAssociatesCards\",\"entity\":\"consolidate\",\"attribute\":\"cRelId\",\"qualifier\":\"45430608\"}"}'

And when i try to parse it fails:

JSON.parse(input)

With this error:

SyntaxError: Unexpected token b in JSON at position 13

What can i do for fix this and get a nice Json Object?

2 Answers 2

1

If you have control over the definition of the JSON like in the code in your question, declare it with String.raw so the backslashes are interpreted as literal backslashes.

The inner object property contains more JSON, so you can parse that as well if you want:

const input = String.raw`{"object":"{\"base\":\"brn\",\"scope\":\"all\",\"channel\":\"sve\",\"service\":\"getAssociatesCards\",\"entity\":\"consolidate\",\"attribute\":\"cRelId\",\"qualifier\":\"45430608\"}"}`;
const parsed = JSON.parse(input);
console.log(JSON.parse(parsed.object));

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, i haven't control over the definition of the JSON. I read the JSON from a file and i'm trying to parse it.
0

If you are reading this from some log file and you cannot control how it is defined, you could always strip out the inner json and parse it on its own.

var input = '{"object":"{\"base\":\"brn\",\"scope\":\"all\",\"channel\":\"sve\",\"service\":\"getAssociatesCards\",\"entity\":\"consolidate\",\"attribute\":\"cRelId\",\"qualifier\":\"45430608\"}"}';

var innerJSON = input.substring(11, input.length - 2);

console.log({
  object: JSON.parse(innerJSON)
});

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.