Reputation: 395
I'm trying to process some decoded json data using the PHP implementation of JSONPath (http://goessner.net/articles/JsonPath/).
I'm fine with using an expression to FIND data in the decoded JSON, but I'd like to be able to SET data using a JSONPath expression. Has anyone been able to do this in PHP using JSONPath, if so, how?
Upvotes: 0
Views: 2255
Reputation: 395
It seems that this implementation of JSONPath does not support set operations.
I've written a simple function that can be added to jsonPath.php to add this functionality. I've pasted it here in case it might be of use to anyone else:
/**
* @param array $obj Decoded json file to alter
* @param string $expr JSONPath expression (http://goessner.net/articles/JsonPath/)
* @param mixed $value Value to set all matching entries to
*/
function jsonPathSet(&$obj, $expr, $value)
{
$paths = jsonPath($obj, $expr, array('resultType' => 'PATH'));
$jsonPath = new JsonPath();
foreach ($paths as $path) {
$p = $jsonPath->normalize($path);
$keys = explode(';', $p);
$current = &$obj;
foreach ($keys as $key) {
if($key=='$') {
continue;
} else if (is_array($current)) {
$current = &$current[$key];
} else {
$current = &$current->$key;
}
}
$current = $value;
}
}
Thanks to Mike Brant for the suggestions!
Upvotes: 3
Reputation: 71384
In briefly looking at the documentation, it would appear that JSONPath doesn't support set operations. If one were so inclined, I would imagine that you could modify JSONPath to optionally return an array of pointers (i.e. object references) as a resultType
such that you could operate on the values directly.
Upvotes: 1