Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError: Unexpected token C in JSON at position 0 - Ionic 2 Http GET request

I am trying to perform a GET request and retrieve the data from the response.

this.http.get('http://localhost:8888/maneappback/more-items.php').subscribe(res => {
    console.log(res.json());
}, (err) => {
    console.log(err);
});

I am getting the error SyntaxError: Unexpected token C in JSON at position 0. I am also assuming that the error is related to the request.

On my server side, I have the data being sent like this (PHP):

echo json_encode($array);

like image 742
ewizard Avatar asked Jun 03 '17 21:06

ewizard


3 Answers

The message you see is that your JSON response is not formatted correctly

GOOD JSON:

{ "name":"John", "age":31, "city":"New York" }

BAD JSON

    { 'name': 'john' }
    { name: "john" }

OR

{ 'name' = 'john' }

In your case, the JSON begins with character C keep in mind that a valid Javascript object could be invalid JSON form

like image 125
Gianfrancesco Aurecchia Avatar answered Oct 08 '22 03:10

Gianfrancesco Aurecchia


I was just neglecting to realize that I still had two echo statements in the script...that is why it wasn't recognized as JSON.

like image 20
ewizard Avatar answered Oct 08 '22 02:10

ewizard


in my case:

previous with error: JSON.parse("{ createdTimestamp: -1 }")

and correct: JSON.parse('{"createdTimestamp":-1}')

like image 23
Nicolas Sturm Avatar answered Oct 08 '22 04:10

Nicolas Sturm