3 import static java.lang.String.format;
5 import java.io.UnsupportedEncodingException;
6 import java.net.URLDecoder;
7 import java.net.URLEncoder;
8 import java.util.ArrayList;
9 import java.util.Collections;
10 import java.util.List;
13 Copyright (c) 2002 JSON.org
15 Permission is hereby granted, free of charge, to any person obtaining a copy
16 of this software and associated documentation files (the "Software"), to deal
17 in the Software without restriction, including without limitation the rights
18 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19 copies of the Software, and to permit persons to whom the Software is
20 furnished to do so, subject to the following conditions:
22 The above copyright notice and this permission notice shall be included in all
23 copies or substantial portions of the Software.
25 The Software shall be used for Good, not Evil.
27 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
37 * A JSON Pointer is a simple query language defined for JSON documents by
38 * <a href="https://tools.ietf.org/html/rfc6901">RFC 6901</a>.
40 * In a nutshell, JSONPointer allows the user to navigate into a JSON document
41 * using strings, and retrieve targeted objects, like a simple form of XPATH.
42 * Path segments are separated by the '/' char, which signifies the root of
43 * the document when it appears as the first char of the string. Array
44 * elements are navigated using ordinals, counting from 0. JSONPointer strings
45 * may be extended to any arbitrary number of segments. If the navigation
46 * is successful, the matched item is returned. A matched item may be a
47 * JSONObject, a JSONArray, or a JSON value. If the JSONPointer string building
48 * fails, an appropriate exception is thrown. If the navigation fails to find
49 * a match, a JSONPointerException is thrown.
54 public class JSONPointer {
56 // used for URL encoding and decoding
57 private static final String ENCODING = "utf-8";
60 * This class allows the user to build a JSONPointer in steps, using
61 * exactly one segment in each step.
63 public static class Builder {
65 // Segments for the eventual JSONPointer string
66 private final List<String> refTokens = new ArrayList<String>();
69 * Creates a {@code JSONPointer} instance using the tokens previously set using the
70 * {@link #append(String)} method calls.
72 public JSONPointer build() {
73 return new JSONPointer(this.refTokens);
77 * Adds an arbitrary token to the list of reference tokens. It can be any non-null value.
79 * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the
80 * argument of this method MUST NOT be escaped. If you want to query the property called
81 * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no
82 * need to escape it as {@code "a~0b"}.
84 * @param token the new token to be appended to the list
85 * @return {@code this}
86 * @throws NullPointerException if {@code token} is null
88 public Builder append(String token) {
90 throw new NullPointerException("token cannot be null");
92 this.refTokens.add(token);
97 * Adds an integer to the reference token list. Although not necessarily, mostly this token will
98 * denote an array index.
100 * @param arrayIndex the array index to be added to the token list
101 * @return {@code this}
103 public Builder append(int arrayIndex) {
104 this.refTokens.add(String.valueOf(arrayIndex));
110 * Static factory method for {@link Builder}. Example usage:
113 * JSONPointer pointer = JSONPointer.builder()
115 * .append("other~key").append("another/key")
121 * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained
122 * {@link Builder#append(String)} calls.
124 public static Builder builder() {
125 return new Builder();
128 // Segments for the JSONPointer string
129 private final List<String> refTokens;
132 * Pre-parses and initializes a new {@code JSONPointer} instance. If you want to
133 * evaluate the same JSON Pointer on different JSON documents then it is recommended
134 * to keep the {@code JSONPointer} instances due to performance considerations.
136 * @param pointer the JSON String or URI Fragment representation of the JSON pointer.
137 * @throws IllegalArgumentException if {@code pointer} is not a valid JSON pointer
139 public JSONPointer(final String pointer) {
140 if (pointer == null) {
141 throw new NullPointerException("pointer cannot be null");
143 if (pointer.isEmpty() || pointer.equals("#")) {
144 this.refTokens = Collections.emptyList();
148 if (pointer.startsWith("#/")) {
149 refs = pointer.substring(2);
151 refs = URLDecoder.decode(refs, ENCODING);
152 } catch (UnsupportedEncodingException e) {
153 throw new RuntimeException(e);
155 } else if (pointer.startsWith("/")) {
156 refs = pointer.substring(1);
158 throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'");
160 this.refTokens = new ArrayList<String>();
162 int prevSlashIdx = 0;
164 prevSlashIdx = slashIdx + 1;
165 slashIdx = refs.indexOf('/', prevSlashIdx);
166 if(prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) {
167 // found 2 slashes in a row ( obj//next )
168 // or single slash at the end of a string ( obj/test/ )
169 this.refTokens.add("");
170 } else if (slashIdx >= 0) {
171 final String token = refs.substring(prevSlashIdx, slashIdx);
172 this.refTokens.add(unescape(token));
174 // last item after separator, or no separator at all.
175 final String token = refs.substring(prevSlashIdx);
176 this.refTokens.add(unescape(token));
178 } while (slashIdx >= 0);
179 // using split does not take into account consecutive separators or "ending nulls"
180 //for (String token : refs.split("/")) {
181 // this.refTokens.add(unescape(token));
185 public JSONPointer(List<String> refTokens) {
186 this.refTokens = new ArrayList<String>(refTokens);
189 private String unescape(String token) {
190 return token.replace("~1", "/").replace("~0", "~")
191 .replace("\\\"", "\"")
192 .replace("\\\\", "\\");
196 * Evaluates this JSON Pointer on the given {@code document}. The {@code document}
197 * is usually a {@link JSONObject} or a {@link JSONArray} instance, but the empty
198 * JSON Pointer ({@code ""}) can be evaluated on any JSON values and in such case the
199 * returned value will be {@code document} itself.
201 * @param document the JSON document which should be the subject of querying.
202 * @return the result of the evaluation
203 * @throws JSONPointerException if an error occurs during evaluation
205 public Object queryFrom(Object document) throws JSONPointerException {
206 if (this.refTokens.isEmpty()) {
209 Object current = document;
210 for (String token : this.refTokens) {
211 if (current instanceof JSONObject) {
212 current = ((JSONObject) current).opt(unescape(token));
213 } else if (current instanceof JSONArray) {
214 current = readByIndexToken(current, token);
216 throw new JSONPointerException(format(
217 "value [%s] is not an array or object therefore its key %s cannot be resolved", current,
225 * Matches a JSONArray element by ordinal position
226 * @param current the JSONArray to be evaluated
227 * @param indexToken the array index in string form
228 * @return the matched object. If no matching item is found a
229 * @throws JSONPointerException is thrown if the index is out of bounds
231 private Object readByIndexToken(Object current, String indexToken) throws JSONPointerException {
233 int index = Integer.parseInt(indexToken);
234 JSONArray currentArr = (JSONArray) current;
235 if (index >= currentArr.length()) {
236 throw new JSONPointerException(format("index %d is out of bounds - the array has %d elements", index,
237 currentArr.length()));
240 return currentArr.get(index);
241 } catch (JSONException e) {
242 throw new JSONPointerException("Error reading value at index position " + index, e);
244 } catch (NumberFormatException e) {
245 throw new JSONPointerException(format("%s is not an array index", indexToken), e);
250 * Returns a string representing the JSONPointer path value using string
254 public String toString() {
255 StringBuilder rval = new StringBuilder("");
256 for (String token: this.refTokens) {
257 rval.append('/').append(escape(token));
259 return rval.toString();
263 * Escapes path segment values to an unambiguous form.
264 * The escape char to be inserted is '~'. The chars to be escaped
265 * are ~, which maps to ~0, and /, which maps to ~1. Backslashes
266 * and double quote chars are also escaped.
267 * @param token the JSONPointer segment value to be escaped
268 * @return the escaped value for the token
270 private String escape(String token) {
271 return token.replace("~", "~0")
273 .replace("\\", "\\\\")
274 .replace("\"", "\\\"");
278 * Returns a string representing the JSONPointer path value using URI
279 * fragment identifier representation
281 public String toURIFragment() {
283 StringBuilder rval = new StringBuilder("#");
284 for (String token : this.refTokens) {
285 rval.append('/').append(URLEncoder.encode(token, ENCODING));
287 return rval.toString();
288 } catch (UnsupportedEncodingException e) {
289 throw new RuntimeException(e);