diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cb22817..ade0b772 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [1.0.1] - 2023-03-17 +### Fixed +* JSON step: improve attempt to fix JSON string having keys without quotes. + ## [1.0.0] - 2023-02-08 ### Added diff --git a/src/Steps/Json.php b/src/Steps/Json.php index af16518f..b8f84498 100644 --- a/src/Steps/Json.php +++ b/src/Steps/Json.php @@ -89,18 +89,32 @@ protected function mapProperties(Dot $dot): array */ protected function fixJsonString(string $jsonString): string { - return preg_replace_callback('/(\w+):/i', function ($match) { - $key = $match[1]; - - if (!str_starts_with($key, '"')) { - $key = '"' . $key; - } - - if (!str_ends_with($key, '"')) { - $key = $key . '"'; - } - - return $key . ':'; - }, $jsonString) ?? $jsonString; + return preg_replace_callback( + '/(?:(\w+):(\s*".+?"\s*(?:,|}))|(\w+):(\s*[^"]+?\s*(?:,|})))/i', + function ($match) { + if (count($match) === 3) { + $key = $match[1]; + + $value = $match[2]; + } elseif (count($match) === 5) { + $key = $match[3]; + + $value = $match[4]; + } else { + return $match[0]; + } + + if (!str_starts_with($key, '"')) { + $key = '"' . $key; + } + + if (!str_ends_with($key, '"')) { + $key = $key . '"'; + } + + return $key . ':' . $value; + }, + $jsonString + ) ?? $jsonString; } } diff --git a/tests/Steps/JsonTest.php b/tests/Steps/JsonTest.php index a40b36ba..d501fa21 100644 --- a/tests/Steps/JsonTest.php +++ b/tests/Steps/JsonTest.php @@ -153,3 +153,23 @@ expect($outputs[0]->get())->toBe(['foo' => 'one', 'bar' => 'two', 'baz' => 'three']); }); + +it('also correctly fixes keys without quotes, even when values contain colons', function () { + $jsonString = <<toHaveCount(1); + + expect($outputs[0]->get())->toBe([ + 'foo' => 'https://www.example.com', + 'bar' => 2, + 'baz' => 'some: thing', + ]); +});