I've a json structure :
{
"Photos":{
"Photo":[
{
"ID" : 111,
"type" : "JPEG",
"URL": "blabla"
},
{
"ID": 222,
"type": "JPG",
"URL": "blaaaaaaaaa"
}
]
}
}
Using php-jsonpath only (By stefan Goessner : http://goessner.net/articles/JsonPath), I want to insert a new data (array) into photo identified by 222 such that final output becomes :
{
"Photos":{
"Photo":[
{
"ID" : 111,
"type" : "JPEG",
"URL": "blabla"
},
{
"ID": 222,
"type": "JPG",
"URL": "blaaaaaaaaa",
"New_data" : {"CROP": "5x7", "Pixel": "none"}
}
]
}
}
in actual sense, i want a future possibility of inserting more sub-data as children or grand children of "New_data" as the case may be.
currently i have:
require_once('json.php'); //the parser file lib
require_once('jsonpath.php'); //the jsonpath evaluator
$parser = new Services_JSON(SERVICE_JSON_LOOSE_TYPE);
$jsonobj = $parser->decode(file_get_contents("filename.json", true));
$result = jsonPath($jsonobj , "$.[1]");
if($result != false){ //this worked flawlessly
foreach ($result as $path) {
$keys = explode(';', $path);
foreach ($keys as $key) {
if($key=='$') {
continue;
} else if (is_array($jsonobj)) {
$jsonobj[$key][] = array("New_data" => array("CROP" => 5x7, "Pixel" => "none"));
} else {
$jsonobj->{$key}[] = array("New_data" => array("CROP" => 5x7, "Pixel" => "none"));
}
}
}
}
file_put_contents("filename.json", $parser->encode($jsonobj)); // write back corrected version
to this extent am confused as the result is unexpectedly positioned elsewhere in filename.json. where am i doing it wrongly, or how else can i do it rightly ? thanks !