Skip to content

Commit 60dbc58

Browse files
authored
feat(validation): Support array indexing in JSON path validation (#21)
* feat(validation): Support array indexing in JSON path validation - Updated the JSON path validation regex to allow array indexing (e.g., `$.data[0].attribute`). - Ensured compatibility with dot notation for nested objects (e.g., `$.data.object.attribute`). - Improved validation to support mixed array and object paths (e.g., `$.data[0].nested[2].value`). - Added stricter checks to prevent malformed paths.
1 parent 49ca4db commit 60dbc58

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/Extractors/JsonExtractor.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,11 @@ public function validate(): bool
4444
if (empty($this->selector) || $this->selector === '$.') {
4545
throw new InvalidJsonPathException('JSON path cannot be empty');
4646
}
47-
// Validate the selector ex: $.meta.token
47+
// Validate the selector ex: $.meta.token or $.data[0].name
4848
// Validate the selector follows proper JSON path format
4949
// Should start with $ followed by dot and valid path segments
50-
if (! preg_match('/^\$(\.[a-zA-Z0-9_]+)*$/', $this->selector)) {
50+
$pattern = '/^\$(\.[a-zA-Z0-9_]+|\[[0-9]+\])*$/';
51+
if (! preg_match($pattern, $this->selector)) {
5152
throw new InvalidJsonPathException('Invalid JSON path');
5253
}
5354

tests/Units/JsonExtractorTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ public static function validJsonPathProvider(): array
4646
['with_underscore'],
4747
['with.numbers.123'],
4848
['mixed.path_with.numbers123'],
49+
['mixed[0].path'],
50+
['mixed[0].path[1]'],
51+
['mixed[0].path[1].with[2].numbers[3]'],
4952
];
5053
}
5154

@@ -67,6 +70,12 @@ public static function invalidJsonPathProvider(): array
6770
['$invalid.start'],
6871
['invalid$.middle'],
6972
['path.with.$'],
73+
['$.data[abc]'],
74+
['$.data[0].name[abc]'],
75+
['$.data[0].name[0].'],
76+
['$.data[0].name[0].[1]'],
77+
['$.data[0].name[0].[1].'],
78+
['$.data[0].name[0].[1].name'],
7079
];
7180
}
7281

0 commit comments

Comments
 (0)