|
1 | 1 | package com.gravity9.jsonpatch;
|
2 | 2 |
|
| 3 | +import java.util.Arrays; |
| 4 | + |
3 | 5 | public class JsonPathParser {
|
4 | 6 |
|
5 |
| - private JsonPathParser() {} |
| 7 | + private JsonPathParser() { |
| 8 | + } |
6 | 9 |
|
7 |
| - private static final String ARRAY_ELEMENT_REGEX = "(?<=\\.)(\\d+)"; |
| 10 | + private static final String ARRAY_ELEMENT_REGEX = "\\A((\\d+)[^a-zA-Z]*)\\z"; |
8 | 11 |
|
9 |
| - /** |
10 |
| - * Method parses JsonPointer or JsonPath path to JsonPath syntax |
11 |
| - * @param path String containing JsonPath or JsonPointer expression |
12 |
| - * @return String containing JsonPath expression |
13 |
| - * @throws JsonPatchException throws when invalid JsonPointer expression provided |
14 |
| - */ |
15 |
| - public static String parsePathToJsonPath(String path) throws JsonPatchException { |
16 |
| - if (path.startsWith("$")) { |
17 |
| - return path; |
18 |
| - } else if (path.contains("?")) { |
19 |
| - throw new JsonPatchException("Invalid path, `?` are not allowed in JsonPointer expressions."); |
20 |
| - } else if (path.contains("//")) { |
21 |
| - throw new JsonPatchException("Invalid path, `//` is not allowed in JsonPointer expressions."); |
22 |
| - } |
| 12 | + /** |
| 13 | + * Method parses JsonPointer or JsonPath path to JsonPath syntax |
| 14 | + * |
| 15 | + * @param path String containing JsonPath or JsonPointer expression |
| 16 | + * @return String containing JsonPath expression |
| 17 | + * @throws JsonPatchException throws when invalid JsonPointer expression provided |
| 18 | + */ |
| 19 | + public static String parsePathToJsonPath(String path) throws JsonPatchException { |
| 20 | + if (path.startsWith("$")) { |
| 21 | + return path; |
| 22 | + } else if (path.contains("?")) { |
| 23 | + throw new JsonPatchException("Invalid path, `?` are not allowed in JsonPointer expressions."); |
| 24 | + } else if (path.contains("//")) { |
| 25 | + throw new JsonPatchException("Invalid path, `//` is not allowed in JsonPointer expressions."); |
| 26 | + } |
23 | 27 |
|
24 |
| - return "$" + path.replace('/', '.') |
25 |
| - .replace("~1", "/") // / must be escaped in JsonPointer using ~1 |
26 |
| - .replace("~0", "~") // ~ must be escaped in JsonPointer using ~0 |
27 |
| - .replaceAll(ARRAY_ELEMENT_REGEX, "[$1]"); |
28 |
| - } |
| 28 | + return "$" + Arrays.stream(path.replace('/', '.') |
| 29 | + .replace("~1", "/") // / must be escaped in JsonPointer using ~1 |
| 30 | + .replace("~0", "~") // ~ must be escaped in JsonPointer using ~0 |
| 31 | + .split("\\.")) // split string to analyze every path field separately |
| 32 | + .filter(s -> !s.isEmpty()) // skip empty string on the beginning of the array |
| 33 | + .map(s -> s.replaceAll(ARRAY_ELEMENT_REGEX, "[$1]")) |
| 34 | + .reduce("", (s, s2) -> s + "." + s2); //connect the path |
| 35 | + } |
29 | 36 | }
|
0 commit comments