0

I am getting the response from one of the API calls something like this :

{status: 'true',description: '0617971781'}

I would like to convert into an associative array with ´status´ and ´description´ being the key elements.

I tried the following explode :

explode($str, ",")

But, I am not able to figure out how, still, Is there a quicker way to do it ?

Thanks

Kiran
  • 8,034
  • 36
  • 110
  • 176

2 Answers2

1

As said in comments, the string {status: 'true',description: '0617971781'} is not a valid json, but if you can modify the string you get to make it valid, you can use json_decode.

This question can help you to convert the invalid json into a valid one.

// this is a valid json
$json = '{"status": "true","description": "0617971781"}';
$obj = json_decode($json); // 
$array = json_decode($json, true); // force the return type as full array

EDIT: added the 2nd parameter option as suggested by plain jane ;) + added link to change string into valid json

Community
  • 1
  • 1
Asenar
  • 6,732
  • 3
  • 36
  • 49
  • 2
    Unfortunately `json_decode` would return `NULL` in this case as this is not valid JSON. – Guilherme Sehn Nov 29 '13 at 11:17
  • 2
    If you do not have control over the API you are calling, you could do some string manipulation to turn this data into valid JSON. The key names must be wrapped into `"`, and the string values should also use double quotes instead of single quotes. – Guilherme Sehn Nov 29 '13 at 11:24
0

Your JSON is not a valid JSON.At first make it valid,if you no control on API call then contact with API provider.

Then try something like this:

$json = '{"status": "true","description": "0617971781"}';
$obj = json_decode($json); // 
$array = json_decode($json, true);
print_r($array);

output:

Array ( [status] => true [description] => 0617971781 ) 
Suvash sarker
  • 3,140
  • 1
  • 18
  • 21