frdho frdho - 6 months ago 80
JSON Question

API response not recognized as JSON

I'm building an application based on a third party API that provides data in JSON format (or is supposed to).

Code snippet:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.test,com");
curl_setopt($ch, CURLOPT_HEADER, FALSE);

curl_setopt($ch, CURLOPT_POST, TRUE);

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"X-API-KEY: *",

$response = curl_exec($ch);


The var_dump() command indicates that the $response variable is a string, and not a JSON.

I've ran through various stack exchange posts on how to clean up strings into JSON, stripslashes, remove invisible hex characters etc, but nothing seems to work.

When I paste this into a JSON validation tool, it says everything is ok.

2 questions:

  1. Am I missing something in my code which causes this to be a string instead of a JSON? I've used APIs before and those just worked out of the box...

  2. Since this is a third party API, a fix (if needed) to correct this situation will likely take long. Is there a script I can use to convert this string into JSON or an array object so that it becomes usable?


Answer Source

Yep, always the HTTP responses are Strings. You have to explicitly typecast them:

$response = json_decode($response);

If you want this as an array instead of an object, set the second parameter as true.

$response = json_decode($response, true);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download