0

I have back slashes that at messes up my JSON. Here is my script:

    $path = "https://api.example.com/datasets/v1/horseman?access_token=[snip]";
    $include_path   = false;
    $opts = array('http' =>
        array(
            'method'  => 'GET',
            'header'  => 'Content-type: application/json',
        )
    );
    $context = stream_context_create($opts);
    $mydata = file_get_contents($path, $include_path, $context);
    $response = array(
        "data" => $mydata, //i need to do this to dump it into datatables.
    );
    echo json_encode($response,JSON_UNESCAPED_SLASHES);

For some reason, I am getting back slashes added as here is the output;

  "data": "[{\"owner\":\"horseman\",\"id\":\"cl5dibmasdasdadsxt\",\"name\":\"goryu\",\"description\":null,\"created\":\"2022-07-09T06:29:53.907Z\",\"modified\":\"2022-07-24T02:57:37.576Z\",\"features\":75,\"size\":16617,\"bounds\":[137.81081,36.658897,137.8403,36.684357]}...

This was a good read about backslashes. Seems JSON_UNESCAPED_SLASHES is for forward slashed. I am also hesitant to run str_replace as I would rather find the problem that a work around.

Here is the contents of $mydata:

[{"owner":"horseman","id":"cl5dirwerwerwe2ts1id4xt","name":"goryu","description":null,"created":"2022-07-09T06:29:53.907Z","modified":"2022-07-24T02:57:37.576Z","features":75,"size":16617,"bounds":[137.81081,36.658897,137.8403,36.684357]},....
spreaderman
  • 918
  • 2
  • 10
  • 39
  • Show what your $mydata contains. – Markus Zeller Aug 27 '22 at 14:43
  • @MarkusZeller thanks. I have added the value of $mydata. I see. It is already JSON, however, I need to add the entire JSON to data like... {"data":[{"owner":"horseman","id":"kjsaflkjdsf"... i can see that I am not doing this right then. – spreaderman Aug 27 '22 at 15:01
  • @MarkusZeller Correct. What I have done was wrong (and stupid). I am trying to throw the entire JSON in {"data":[]} but cannot figure that out. – spreaderman Aug 27 '22 at 15:08
  • 1
    You json_encode() what is already JSON. That's why it is all escaped. – Markus Zeller Aug 27 '22 at 15:08

0 Answers0