I have a JSON string I want to change it.
The JSON string looks like
string '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]' (length=114)
I want to convert this JSON to
string '[{"id":"AT02708872"},{"id":"DE60232348"}]' (length=114)
So I want to remove the dots and the last letter. I am using Symfony2 (PHP)
Anyone has any idea how can I do it.
Thanks
Decode, modify, re-encode.
<?php
$json = '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]';
// Decode the JSON data into an array of objects.
// Symfony probably will have some JSON handling methods so you could look at
// those to keep the code more Symfony friendly.
$array = json_decode($json);
// Loop through the array of objects so you can modify the ID of
// each object. Note the '&'. This is calling $object by reference so
// any changes within the loop will persist in the original array $array
foreach ($array as &$object)
{
// Here we are stripping the periods (.) from the ID and then removing the last
// character with substr()
$object->id = substr(str_replace('.', '', $object->id), 0, -1);
}
// We can now encode $array back into JSON format
$json = json_encode($array);
var_dump($json);
There is probably native JSON handling within Symfony2 so you may want to check that out.
You can use javascript regular expression to replace the unwanted elements with blank string. You should, however, do this before you parse the string to php object.
Is it one string? Run a regular expression on it:
<?
$str = '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]' ;
echo preg_replace('/\.[A-Z]"/','"',$str);
?>
This is assuming that all your id's end in . 1 capital letter.
$json = '[{"id":"AT.02708872.T"},{"id":"DE.60232348.A"}]';
$json = json_decode($json, true);
$result = array();
foreach($json as $item) {
$tmp = explode('.', $item['id']);
$result[] = array('id' => $tmp[0] . $tmp[1]);
}
$result = json_encode($result);
echo $result;