Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to parse a valid JSON

My api sends back a JSON response like this using PHP Silex:

{"response":true,"message":"Bla","userId":"AAA"}

But i can't parse it in my Typescript frontend

this.authService.login(body).then((result : any)  => {
    console.log(result.data); // => {"response":true,"message":"Bla","userId":"AAA"}         
    let parsed = JSON.parse(result.data);
    console.log(parsed.message); // => throws  "SyntaxError: Unexpected token in JSON at position 0\n at JSON.parse (<anonymous>)

My php endpoint using PHP and Silex Framework:

$app->post('/user/login', function (Request $request) use ($app, $config) {
    $email = $request->request->get('user-email');
    $password = $request->request->get('user-password');
    $rsp = loginUser($email,$password);
    return $app->json($rsp);
});

When try and hardcode the json object into code, it does parse!

UPDATE SOLUTION I had to use trim() for result.data to remove whitespaces, somehome the response came with whitespaces and JSON didn't like that. Thank you all for your help.

like image 513
Yassine Avatar asked Sep 03 '18 13:09

Yassine


2 Answers

SOLUTION

i used result.data.trim() for it to work, somehow the response had whitespaces and JSON didn't like that.

like image 156
Yassine Avatar answered Oct 17 '22 03:10

Yassine


You may have a \u0000 char somewhere coming from your PHP code.

Try to remove these characters from your JSON string as soon as you get it from PHP:

this.authService.login(body).then((result : any)  => {
    string = result.data.replace("\u0000", "");
    string = string.replace("\\u0000", "");
    let parsed = JSON.parse(string);
like image 1
Alberto Avatar answered Oct 17 '22 05:10

Alberto