Skip to content
This repository was archived by the owner on Jan 11, 2026. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions src/Peekmo/JsonPath/JsonStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,10 @@ public function toArray()
* Gets elements matching the given JsonPath expression
* @param string $expr JsonPath expression
* @param bool $unique Gets unique results or not
* @param bool $keyFromPath ability to retain pathing in key separated by a |
* @return array
*/
public function get($expr, $unique = false)
public function get($expr, $unique = false, $keyFromPath = false)
{
if ((($exprs = $this->normalizedFirst($expr)) !== false) &&
(is_array($exprs) || $exprs instanceof \Traversable)
Expand All @@ -97,11 +98,23 @@ public function get($expr, $unique = false)
preg_replace(array("/^\\$\[[\"']?/", "/[\"']?\]$/"), "", $expr)
);

$path = "";
for ($i = 0; $i < count($keys); $i++) {

$path .= $keys[$i];
if ($i < count($keys) - 1) {
$path .= '|';
}

$o =& $o[$keys[$i]];
}

$values[] = & $o;
if ($keyFromPath) {
$values[$path] = & $o;
}
else {
$values[] = & $o;
}
}

if (true === $unique) {
Expand Down
17 changes: 17 additions & 0 deletions tests/JsonStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,23 @@ public function testGetAllByKeyFiltered()
$expected = ["fiction", "fiction"];
$this->assertEquals($data, $expected);
}

public function testGetMaintainPath()
{
$jsonStore = new JsonStore('{"body":[{"name":"Peter Peterson","age":22,"gender":"Male"},{"name":"John Johnston","age":64}]}');
$data = $jsonStore->get("$.body[*]", false, true);
$expected = array( 'body|0' => array(
'name' => 'Peter Peterson',
'age' => 22,
'gender' => 'Male'
),
'body|1' => array (
'name' => 'John Johnston',
'age' => 64
));

$this->assertEquals($data, $expected);
}

public function tearDown()
{
Expand Down