sumit
sumit

Reputation: 15464

parse json string with forward slashes - javascript

Looks pretty simple but I am unable to figure it out

var str="[{name:\"House\",id:\"1\"},{name:\"House and Land\",id:\"5\"},{name:\"Land\",id:\"6\"},{name:\"Terrace\",id:\"11\"}]";
JSON.parse(str.replace(/\s/g, "").replace(/\//g, ''));

I am unable to the convert above string(which comes from 3rd party website) to valid json so that I can iterate it on my side

error

VM5304:1 Uncaught SyntaxError: Unexpected token n in JSON at position 2
    at JSON.parse (<anonymous>)

Upvotes: 0

Views: 3060

Answers (1)

Jay Harris
Jay Harris

Reputation: 4271

JSON requires the keys to be quoted. It appears that your keys are coming in unquoted. So add another .replace statement to insert the quote back in:

.replace(/(\w+):/g, '"$1":');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

Property names must be double-quoted strings; trailing commas are forbidden.

COMPLETE SOLUTION:

.replace(/(,|{)\s*(\w+)\s*:/g, '$1"$2":');

Upvotes: 2

Related Questions