0

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>)
6
  • 1
    Are you sure the source string is not valid? It looks like the result of a JSON encoded value being included in another JSON encoded value. Commented Nov 23, 2017 at 23:19
  • 1
    JSON requires the index or key to be quoted Commented Nov 23, 2017 at 23:19
  • That's not a valid JSON, but it's ok for console.log( eval( str ) ) Commented Nov 23, 2017 at 23:26
  • 1
    I'm with @Marty - this appears very familiar to valid JSON that is being displayed in debugging tools. Are you in actual possession of a string with slashes (i.e. you use it like var string = ... exactly as you have posted?), or is it being returned from some sort of ajax/api call and the slashes appear in your developer tools? Commented Nov 23, 2017 at 23:27
  • Ok, I've got it - somebody has JSON.stringify-ied an already valid JSON string (which adds the forward slashes) and now you are trying to parse it - that's what is really going on here. Commented Nov 23, 2017 at 23:31

1 Answer 1

2

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":');
Sign up to request clarification or add additional context in comments.

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.