Muaaz Khalid
Muaaz Khalid

Reputation: 2249

JSON: Error while Parsing

I've the following JSON(Valid) sting.

[["abc","{\"icon\":\"adjust\",\"prefix\":\"fa\",\"markerColor\":\"red\"}"],["xyz","{\"icon\":\"archive\",\"prefix\":\"fa\",\"markerColor\":\"green\"}"],["azs","{\"icon\":\"asterisk\",\"prefix\":\"fa\",\"markerColor\":\"darkred\"}"]]

it gives error when I try to Parse using the JSON.parse function here is the code that I'm using for parsing.

JSON.parse('[["abc","{\"icon\":\"adjust\",\"prefix\":\"fa\",\"markerColor\":\"red\"}"],["xyz","{\"icon\":\"archive\",\"prefix\":\"fa\",\"markerColor\":\"green\"}"],["azs","{\"icon\":\"asterisk\",\"prefix\":\"fa\",\"markerColor\":\"darkred\"}"]]');

and it gives an error in console Uncaught SyntaxError: Unexpected token i

here is the Correct Output by same string using online JSON viewer. Correct Output by same string using online JSON viewer

Upvotes: 1

Views: 243

Answers (3)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

You need to escape (\) the escape (\") itself, within the string literal.

Additionally, you can parse this data in two passes.

const data = `[["abc","{\\"icon\\":\\"adjust\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"red\\"}"],["xyz","{\\"icon\\":\\"archive\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"green\\"}"],["azs","{\\"icon\\":\\"asterisk\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"darkred\\"}"]]`;

const firstPass = JSON.parse(data);
const secondPass = firstPass.map(([k, v]) => [k, JSON.parse(v)]);

console.log(secondPass);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 1

That Guy
That Guy

Reputation: 379

When you use JSON viewer, it's different from when you use the code in your JS code. Like @Jonathan stated, you should double escape you JSON string.

JSON.parse('[["abc","{\\"icon\\":\\"adjust\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"red\\"}"],["xyz","{\\"icon\\":\\"archive\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"green\\"}"],["azs","{\\"icon\\":\\"asterisk\\",\\"prefix\\":\\"fa\\",\\"markerColor\\":\\"darkred\\"}"]]');

Upvotes: 2

hamed
hamed

Reputation: 8033

Your json structure is invalid. You should use this instead(without slashes):

  '[["abc",["icon":"adjust","prefix":"fa","markerColor":"red"]],["xyz",["icon":"archive","prefix":"fa","markerColor":"green"]],["azs",["icon":"asterisk","prefix":"fa","markerColor":"darkred"]]'

Upvotes: 0

Related Questions