Phan Van Linh Phan Van Linh - 2 months ago 7
PHP Question

Add json to array without lose format

I tried to add the simple json below to my array in my API

$result = array();
...
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$json = json_encode($arr);
$result['json'] = $json;

return $result;


But after add it to my array, it loose the format like this.

Please look at the red arrow point to and compare with screenshot 2.

enter image description here

What I want is my json should display like

enter image description here

How can I prevent it. Any help or suggestion would be great appreciated

Answer

What seems to be happening here is double encoding, your $result array gets encoded as well, then it encodes the $result['json'] again, causing the output you are seeing.

$result = array();
...
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$json =  json_encode($arr);               
$result['json'] = $json;

return $result; // either you are using a framework, or not showing a step, but this also seems to be encoded before being sent back to the client.

Given what I can infer from you have then shown us, do not encode your array before assigning it to $result['json']

$result = array();
...          
$result['json'] = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

return $result;

Should then give you what you want.