Skip to content

Commit

Permalink
Improve fixing JSON having keys without quotes
Browse files Browse the repository at this point in the history
Improve attempt to fix JSON strings having keys without quotes in the
Json step.
  • Loading branch information
otsch committed Mar 17, 2023
1 parent b808d7d commit bfc542f
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 13 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
40 changes: 27 additions & 13 deletions src/Steps/Json.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
20 changes: 20 additions & 0 deletions tests/Steps/JsonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <<<JSON
{
foo: "https://www.example.com",
bar: 2,
"baz": "some: thing"
}
JSON;

$outputs = helper_invokeStepWithInput(Json::get(['foo', 'bar', 'baz']), $jsonString);

expect($outputs)->toHaveCount(1);

expect($outputs[0]->get())->toBe([
'foo' => 'https://www.example.com',
'bar' => 2,
'baz' => 'some: thing',
]);
});

0 comments on commit bfc542f

Please sign in to comment.