user4321187
user4321187

Reputation:

Replacing special chars in a string in order to use JSON.parse()

I have a string

var test = '[{"ident": "success"}, {"records": {"0": {"organisation": "Microsoft"}, "1": {"organizacja": "\"a"}}}]';

How can i replace \" with \\" so i can parse it with JSON.parse? Anyone know this?

Upvotes: 0

Views: 187

Answers (3)

Priyank
Priyank

Reputation: 3868

Try this:

test.replace(/\\"/g, '\\\\"');

Upvotes: 0

degr
degr

Reputation: 1565

Your question must sounds like - how I can get valid json string from object using [java, php, python], and then use it with javascript.

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

I think you want something like this,

> var test = '[{"ident": "success"}, {"records": {"0": {"organisation": "Microsoft"}, "1": {"organizacja": "\\"a"}}}]';
> console.log(test)
[{"ident": "success"}, {"records": {"0": {"organisation": "Microsoft"}, "1": {"organizacja": "\"a"}}}]
> console.log(test.replace(/\\"/g, '\\\\"'))
[{"ident": "success"}, {"records": {"0": {"organisation": "Microsoft"}, "1": {"organizacja": "\\"a"}}}]

Upvotes: 0

Related Questions