barha
barha

Reputation: 699

JSON parse of quote inside double quote

My value is a string:

"['Eitaj', 'Jason Json', 'Eitaj M', "Jason Json's"]"

I am trying to parse it using JSON.parse(), however, I get error

Uncaught SyntaxError: Unexpected token ' in JSON at position 1

I find out the the working correct string is:

JSON.parse('["Eitaj", "Jason Json", "Eitaj M", "Jason Json\'s"]')

Is there any trick I can use other than placing single quotes with double quotes?

Upvotes: 0

Views: 272

Answers (1)

Chathura Widanage
Chathura Widanage

Reputation: 663

Check whether this works for you.

let s = "['Eitaj', 'Jason Json', 'Eitaj M', \"Jason Json's\"]";

let parsed = JSON.parse(s.split(",").map(seg => {
  return seg.replace(new RegExp("'.*'", "g"), function(match) {
    return '"' + match.substring(1, match.length - 1) + '"';
  })
}).join(","));

console.log(parsed);

Update 1

This will handle flaws of the above snippet which are mentioned in the comments. However there can be still other edge cases which should be handled based on your requirement.

let s = "['Eitaj', 'Jason Json', 'Eitaj M', \"Jason Json's\",\"Test'test'Test\",'Acme, Inc.',\"'Test'\"]";

let parsed = JSON.parse("[" + s.substring(1, s.length - 1).match(new RegExp(`((['\""]).*?(\\2))`, "g")).map(seg => {
  return seg.trim().replace(new RegExp("^'.*'$", "g"), function(match) {
    return '"' + match.substring(1, match.length - 1) + '"';
  })
}).join(",") + "]")

console.log(parsed);

Upvotes: 2

Related Questions