Alessandro Alessandro - 2 months ago 4
JSON Question

How to edit JSON objects

I'm on PHP and I need to edit a JSON output to return only objects

and divided by one hundred


$json = {"data":[0,55,78,-32,-46,37]}


$json = {"data":[0,0.55,0.78,0.37]}

How this can be done?


Well, I know this is not the best practice, but if it's as simple as this, you can do the following.

$json = '{"data":[0,55,78,-32,-46,37]}';

// decoding the string to objects & arrays
$x = json_decode($json);

// applying a function on each value of the array
$x->data = array_map(
                   if( $a >= 0 ) return $a/100; 
                   else return null; 
// Removing empty values of the array
$x->data = array_filter($x->data);

// making a JSON array
$jsonData = json_encode(array_values($x->data));

// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';

// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;

Hope it helps !

Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...