user6171080
user6171080

Reputation:

How to edit JSON objects

I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred

Eg.

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

Needed

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

How this can be done?

Upvotes: 2

Views: 1967

Answers (2)

Bobot
Bobot

Reputation: 1118

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(
               function($a)
               { 
                   if( $a >= 0 ) return $a/100; 
                   else return null; 
               }, 
               $x->data
            );
// 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 ...


EDIT :

Find out the way :D

Once empty values removed from the array, just do :

$x->data = array_values($x->data);
$json = json_encode($x);

This will do the trick and it will not create issues with the rest of the object.

Upvotes: 1

Joel Hernandez
Joel Hernandez

Reputation: 2213

Alessandro:

Here's my approach, feel free to try. json_decode and a simple foreach can help you...

Code:

$json = array();
$result = array();

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

$decoded_json=json_decode($json, TRUE);

foreach ($decoded_json['data'] as &$value) {
    if ($value >= 0){
        $value = $value / 100;
        $result[]=$value;
    }

}

echo json_encode($result);

?>

Result:

[0,
0.55,
0.78,
0.37
]

Upvotes: 0

Related Questions