Gaurav Lath
Gaurav Lath

Reputation: 123

Error in converting string to json object

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>) 

Upvotes: 1

Views: 2999

Answers (2)

AP.
AP.

Reputation: 8921

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)

Upvotes: 2

E. Sundin
E. Sundin

Reputation: 4181

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"]]}`

Upvotes: 3

Related Questions