User7723337
User7723337

Reputation: 12018

JSON Parsing in AngularJS Service

I have Angular service and in that service I have a code:

this.testMethod = function( ) {
    this.jsonTest = "[{'id':'123','title':'XYZ','id2':'456','status':2}]";
    this.parseTest(this.jsonTest);
};

this.parseTest = function(jsonTest) {
    var jsonTestObj = JSON.parse(jsonTest); // I get error hear
}

Test method is getting called on ng-click event.
Error that I am getting while testing in latest chrome browser:

SyntaxError: Unexpected token ' at Object.parse (native)
......

I tried multiple things to fix it but nothing seems to work.
Every time I get undefined value error.

Basically I want to parse JSON object and get the values.
What am I doing wrong?

Upvotes: 0

Views: 293

Answers (3)

guiguiblitz
guiguiblitz

Reputation: 407

Your JSON is not valid. Always check your JSON integrity in those cases, i personaly use

http://jsonlint.com/

Upvotes: -2

cst1992
cst1992

Reputation: 3941

Use this

this.jsonTest = '[{"id":"123","title":"XYZ","id2":"456","status": "2"}]';

Or this

this.jsonTest = "[{\"id\":\"123\",\"title\":\"XYZ\",\"id2\":\"456\",\"status\": \"2\"}]";

You either need to use ' outside or " outside and escape the quotes inside.

Both the key and value need to be in double quotes.

Upvotes: 2

Slytherin
Slytherin

Reputation: 474

You need to use double quotes in your string, other than that your code should work.

To quote from specification

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

Upvotes: 2

Related Questions