3 import static java.lang.String.format;
5 import java.io.UnsupportedEncodingException;
6 import java.net.URLDecoder;
7 import java.net.URLEncoder;
11 Copyright (c) 2002 JSON.org
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
23 The Software shall be used for Good, not Evil.
25 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
35 * A JSON Pointer is a simple query language defined for JSON documents by
36 * <a href="https://tools.ietf.org/html/rfc6901">RFC 6901</a>.
38 * In a nutshell, JSONPointer allows the user to navigate into a JSON document
39 * using strings, and retrieve targeted objects, like a simple form of XPATH.
40 * Path segments are separated by the '/' char, which signifies the root of
41 * the document when it appears as the first char of the string. Array
42 * elements are navigated using ordinals, counting from 0. JSONPointer strings
43 * may be extended to any arbitrary number of segments. If the navigation
44 * is successful, the matched item is returned. A matched item may be a
45 * JSONObject, a JSONArray, or a JSON value. If the JSONPointer string building
46 * fails, an appropriate exception is thrown. If the navigation fails to find
47 * a match, a JSONPointerException is thrown.
52 public class JSONPointer {
54 // used for URL encoding and decoding
55 private static final String ENCODING = "utf-8";
58 * This class allows the user to build a JSONPointer in steps, using
59 * exactly one segment in each step.
61 public static class Builder {
63 // Segments for the eventual JSONPointer string
64 private final List<String> refTokens = new ArrayList<String>();
67 * Creates a {@code JSONPointer} instance using the tokens previously set using the
68 * {@link #append(String)} method calls.
70 public JSONPointer build() {
71 return new JSONPointer(refTokens);
75 * Adds an arbitary token to the list of reference tokens. It can be any non-null value.
77 * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the
78 * argument of this method MUST NOT be escaped. If you want to query the property called
79 * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no
80 * need to escape it as {@code "a~0b"}.
82 * @param token the new token to be appended to the list
83 * @return {@code this}
84 * @throws NullPointerException if {@code token} is null
86 public Builder append(String token) {
88 throw new NullPointerException("token cannot be null");
95 * Adds an integer to the reference token list. Although not necessarily, mostly this token will
96 * denote an array index.
98 * @param arrayIndex the array index to be added to the token list
99 * @return {@code this}
101 public Builder append(int arrayIndex) {
102 refTokens.add(String.valueOf(arrayIndex));
108 * Static factory method for {@link Builder}. Example usage:
111 * JSONPointer pointer = JSONPointer.builder()
113 * .append("other~key").append("another/key")
119 * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained
120 * {@link Builder#append(String)} calls.
122 public static Builder builder() {
123 return new Builder();
126 // Segments for the JSONPointer string
127 private final List<String> refTokens;
130 * Pre-parses and initializes a new {@code JSONPointer} instance. If you want to
131 * evaluate the same JSON Pointer on different JSON documents then it is recommended
132 * to keep the {@code JSONPointer} instances due to performance considerations.
134 * @param pointer the JSON String or URI Fragment representation of the JSON pointer.
135 * @throws IllegalArgumentException if {@code pointer} is not a valid JSON pointer
137 public JSONPointer(String pointer) {
138 if (pointer == null) {
139 throw new NullPointerException("pointer cannot be null");
141 if (pointer.isEmpty()) {
142 refTokens = Collections.emptyList();
145 if (pointer.startsWith("#/")) {
146 pointer = pointer.substring(2);
148 pointer = URLDecoder.decode(pointer, ENCODING);
149 } catch (UnsupportedEncodingException e) {
150 throw new RuntimeException(e);
152 } else if (pointer.startsWith("/")) {
153 pointer = pointer.substring(1);
155 throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'");
157 refTokens = new ArrayList<String>();
158 for (String token : pointer.split("/")) {
159 refTokens.add(unescape(token));
163 public JSONPointer(List<String> refTokens) {
164 this.refTokens = new ArrayList<String>(refTokens);
167 private String unescape(String token) {
168 return token.replace("~1", "/").replace("~0", "~")
169 .replace("\\\"", "\"")
170 .replace("\\\\", "\\");
174 * Evaluates this JSON Pointer on the given {@code document}. The {@code document}
175 * is usually a {@link JSONObject} or a {@link JSONArray} instance, but the empty
176 * JSON Pointer ({@code ""}) can be evaluated on any JSON values and in such case the
177 * returned value will be {@code document} itself.
179 * @param document the JSON document which should be the subject of querying.
180 * @return the result of the evaluation
181 * @throws JSONPointerException if an error occurs during evaluation
183 public Object queryFrom(Object document) {
184 if (refTokens.isEmpty()) {
187 Object current = document;
188 for (String token : refTokens) {
189 if (current instanceof JSONObject) {
190 current = ((JSONObject) current).opt(unescape(token));
191 } else if (current instanceof JSONArray) {
192 current = readByIndexToken(current, token);
194 throw new JSONPointerException(format(
195 "value [%s] is not an array or object therefore its key %s cannot be resolved", current,
203 * Matches a JSONArray element by ordinal position
204 * @param current the JSONArray to be evaluated
205 * @param indexToken the array index in string form
206 * @return the matched object. If no matching item is found a
207 * JSONPointerException is thrown
209 private Object readByIndexToken(Object current, String indexToken) {
211 int index = Integer.parseInt(indexToken);
212 JSONArray currentArr = (JSONArray) current;
213 if (index >= currentArr.length()) {
214 throw new JSONPointerException(format("index %d is out of bounds - the array has %d elements", index,
215 currentArr.length()));
217 return currentArr.get(index);
218 } catch (NumberFormatException e) {
219 throw new JSONPointerException(format("%s is not an array index", indexToken), e);
224 * Returns a string representing the JSONPointer path value using string
228 public String toString() {
229 StringBuilder rval = new StringBuilder("");
230 for (String token: refTokens) {
231 rval.append('/').append(escape(token));
233 return rval.toString();
237 * Escapes path segment values to an unambiguous form.
238 * The escape char to be inserted is '~'. The chars to be escaped
239 * are ~, which maps to ~0, and /, which maps to ~1. Backslashes
240 * and double quote chars are also escaped.
241 * @param token the JSONPointer segment value to be escaped
242 * @return the escaped value for the token
244 private String escape(String token) {
245 return token.replace("~", "~0")
247 .replace("\\", "\\\\")
248 .replace("\"", "\\\"");
252 * Returns a string representing the JSONPointer path value using URI
253 * fragment identifier representation
255 public String toURIFragment() {
257 StringBuilder rval = new StringBuilder("#");
258 for (String token : refTokens) {
259 rval.append('/').append(URLEncoder.encode(token, ENCODING));
261 return rval.toString();
262 } catch (UnsupportedEncodingException e) {
263 throw new RuntimeException(e);