diff --git a/src/Galbar/JsonPath/JsonObject.php b/src/Galbar/JsonPath/JsonObject.php index 1043186..34d8fe9 100644 --- a/src/Galbar/JsonPath/JsonObject.php +++ b/src/Galbar/JsonPath/JsonObject.php @@ -219,7 +219,7 @@ public function getJson($options=0) public function get($jsonPath) { list($result, $hasDiverged) = JsonPath::get($this->jsonObject, $jsonPath); - if ($this->smartGet && $result !== false && !$hasDiverged) { + if ($this->smartGet && $result !== false && !$hasDiverged && is_array($result)) { return $result[0]; } return $result; @@ -251,7 +251,7 @@ public function getJsonObjects($jsonPath) $jsonObject->jsonObject = &$value; $objs[] = $jsonObject; } - if ($this->smartGet && !$hasDiverged) { + if ($this->smartGet && !$hasDiverged && is_array($result)) { return $objs[0]; } return $objs; diff --git a/src/Galbar/JsonPath/JsonPath.php b/src/Galbar/JsonPath/JsonPath.php index 96a1cc9..45914a7 100644 --- a/src/Galbar/JsonPath/JsonPath.php +++ b/src/Galbar/JsonPath/JsonPath.php @@ -47,8 +47,12 @@ public static function subtreeGet(&$root, &$partial, $jsonPath, $createInexisten $newSelection = array_merge($newSelection, $result); } if (empty($newSelection) && Language\Token::LENGTH === $childName) { - foreach ($selection as $item) { - $newSelection[] = is_array($item) ? count($item) : strlen($item); + if (count($selection) > 1) { + foreach ($selection as $item) { + $newSelection[] = is_array($item) ? count($item) : strlen($item); + } + } else if (count($selection) == 1) { + $newSelection = is_array($selection[0]) ? count($selection[0]) : strlen($selection[0]); } } if (empty($newSelection)) { diff --git a/tests/Galbar/JsonPath/JsonObjectLengthOperatorTest.php b/tests/Galbar/JsonPath/JsonObjectLengthOperatorTest.php index 374a718..7c85e26 100644 --- a/tests/Galbar/JsonPath/JsonObjectLengthOperatorTest.php +++ b/tests/Galbar/JsonPath/JsonObjectLengthOperatorTest.php @@ -156,7 +156,7 @@ public function testLength() $jsonObject = new JsonObject($this->json); $result = $jsonObject->get($jsonPath); $this->assertEquals( - [3], + 3, $result ); @@ -164,14 +164,14 @@ public function testLength() $jsonPath = '$.music.bands[0].albums[0].length.length'; $result = $jsonObject->get($jsonPath); $this->assertEquals( - [5], + 5, $result ); $jsonPath = '$.music.bands[0].albums[1].title.length'; $result = $jsonObject->get($jsonPath); $this->assertEquals( - [6], + 6, $result ); }