0

I try to use JSON.parse(), but I have error

Uncaught SyntaxError: Unexpected token ' 

working

JSON.parse('{"inputType":"select", "rules" :[{"rule": "literal_values", "restriction": "US"}]}') 

but not working

enter image description here

why the second version not working?

typeof(validRules) is string

6
  • 6
    Works for me...Can you reproduce in a jsFiddle? Commented Jun 17, 2014 at 13:48
  • 1
    There is no reason this would produce different results. Are you sure you have the exact same string in your test environment? Commented Jun 17, 2014 at 13:48
  • sorry, i have updated my question Commented Jun 17, 2014 at 13:54
  • please paste output of "typeof (validRules)" if it is string then your code is ok but if its o/p is object then you are doing it wrong. Commented Jun 17, 2014 at 13:59
  • typeof (validRules) is string Commented Jun 17, 2014 at 14:01

1 Answer 1

1

The screenshot shows the single-quotes as characters within the string's value.

console.log(JSON.parse("'{\"inputType\":\"select\"}'"))
//                      ^                          ^
// SyntaxError: Unexpected token '
console.log(validRules.charAt(0));     // "'" vs. "{"
console.log(validRules.charCodeAt(0)); // 39  vs. 123

While, in your snippet, they're acting as the delimiters for the string literal.

console.log(JSON.parse('{"inputType":"select"}'))
// { inputType: 'select' }

You'll need to remove the single-quotes from the string value for it to be parsed as JSON.

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.