1
a = "{'sentiments': [['1485925200000', '0.0636363636364']]}"
// typeof(a) returns string

Trying to convert this string to json object in angular using JSON.parse(a). However, I am getting an error.

    SyntaxError: Unexpected token ' in JSON at position 1
at JSON.parse (<anonymous>) 
9
  • 4
    Use " instead of ' Commented Apr 5, 2017 at 18:51
  • 1
    JSON.parse( a.replace(/'/g, '"') )! Commented Apr 5, 2017 at 18:53
  • @E.Sundin Before the word sentiments ? Commented Apr 5, 2017 at 18:53
  • Every instance of ', like so a = `{"sentiments": [["1485925200000", "0.0636363636364"]]} Commented Apr 5, 2017 at 18:54
  • you mean... convert string to json string? javascript object? how are you getting this... string? it isn't valid json and therefore cannot be parsed as json. Commented Apr 5, 2017 at 18:55

2 Answers 2

3

Since my comment was poorly formatted I'm providing an answer.

Change your JSON format to the following valid one, replacing all ' with ".

a = `{"sentiments": [["1485925200000", "0.0636363636364"]]}`

Sign up to request clarification or add additional context in comments.

Comments

2

Since you have ' which are not supported by the JSON format, you can do something like:

a = "{'sentiments': [['1485925200000', '0.0636363636364']]}"
JSON.parse(a.replace(/'/g,'"'))

This uses regular expressions to find all instances of ' and replace them with ". So that your JSON can be parsed.

Edit

A more dangerous, yet acceptable approach could also be used in this example by using eval() since ' is considered a valid string declarator in JavaScript, thus you could do:

const myObject = eval(a)

4 Comments

i mean... it's correct, until the string contains a string that contains single quotes. the... correct... way to fix this would be to fix the source, not run a regex on a string that should be json.
Addressed your use case @KevinB
Worked like a charm :)
/\'/g could be just /'/g no need to escape it!

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.