Search code examples
phpjsonsilexpostman

Postman show unexpected 'A' in json response , but json is well formed


I'm developing a backend with Silex framework and i'm testing this piece of code

foreach($P as $key=>$value)
    {
        $strInsert  =$key."=>".$value;      
        array_push($json,$strInsert);                 
    }
    print_r($json);
    return json_encode($json);

On every browser calling the route which contains the foreach it prints well, and the output given is considered well-formed by different json validators. In postman when i click on 'pretty' Json it shows Unexpected 'A'.
On raw,html and other views options the json document is print without problems. Should I keep worrying for this problem or just ignore it? If I shouldn't ignore it, is there a fix ?


Solution

  • After a lot of work on Silex framework to build my backend, Thanks to postman (a chrome app,really handy for testing http protocols),I've figured out that php waits the response in a Json format.

        Example A :
        call route /path/getinfo/ with method get
        execute the code --> result=$app->SomeFunctionThatInterrogatesDB(param1...) **firing error
                             return result;
    

    here's the deal : in that somefunction you make a query to the db and it returns a row (or multiple rows depending from the type of query),PHP thinks that the response is structured in JSON, but it is not, so it fires that error.
    That unexpected 'A' just means "hey,where is my json? I can't understand nothing !"
    The fix or the workaround, is just to encapsulate your result in json format inside the route.

    To be strict change return result with return $app->json(result). This code is based on silex but even if you are using other framework out of silex, the solution is to stringify your final result in json format.Here is a little graph(call me davinci if you want) to understand better the flow.

     |*Frontend*|  route request     |   *Backend*   | query     |*Database*|
     |          |------------------->|               |---------->|          |
     |          |    Response        | json(result)  |  array    |          |
     |          |<-------------------|<--------------|<----------|          |
    

    I hope that my answer can be of help to anyone.