1ee3ce7adadb4f853ecdff4feca5ba54217d8f9a
[nit.git] / lib / json / dynamic.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Dynamic interface to read JSON strings.
18 #
19 # `String::to_json_value` returns a `JsonValue` which can be queried
20 # to get the underlying JSON data.
21 module dynamic
22
23 import error
24 private import static
25
26 # Wraps a JSON value.
27 #
28 # Offer methods to query the type, to dynamicaly cast the underlying value and
29 # to query elements (in case of a JSON object or a JSON array).
30 #
31 # Use `String::to_json_value` to get a `JsonValue` from a string.
32 class JsonValue
33
34 # The wrapped JSON value.
35 var value: nullable Object
36
37 # Is this value null?
38 #
39 # assert "null".to_json_value.is_null
40 # assert not "123".to_json_value.is_null
41 fun is_null: Bool do return value == null
42
43 # Is this value an integer?
44 #
45 # assert "123".to_json_value.is_int
46 # assert not "1.23".to_json_value.is_int
47 # assert not "\"str\"".to_json_value.is_int
48 fun is_int: Bool do return value isa Int
49
50 # Get this value as a `Int`
51 #
52 # require: `self.is_int`
53 #
54 # assert "-10".to_json_value.to_i == -10
55 # assert "123".to_json_value.to_i == 123
56 fun to_i: Int do return value.as(Int)
57
58 # Is this value a float?
59 #
60 # assert "0.0".to_json_value.is_float
61 # assert "123.456".to_json_value.is_float
62 # assert not "123".to_json_value.is_float
63 fun is_float: Bool do return value isa Float
64
65 # Get this value as a `Float`
66 #
67 # require: `self.is_float`
68 #
69 # assert "0.0".to_json_value.to_f == 0.0
70 # assert "123.456".to_json_value.to_f == 123.456
71 fun to_f: Float do return value.as(Float)
72
73 # Is the value numeric?
74 #
75 # assert "1.234".to_json_value.is_numeric
76 # assert "1234".to_json_value.is_numeric
77 # assert not "\"str\"".to_json_value.is_numeric
78 # assert not "1.2.3.4".to_json_value.is_numeric
79 fun is_numeric: Bool do return is_int or is_float
80
81 # Get this value as a `Numeric`
82 #
83 # require: `self.is_numeric`
84 #
85 # assert "1.234".to_json_value.to_numeric == 1.234
86 # assert "1234".to_json_value.to_numeric == 1234
87 fun to_numeric: Numeric
88 do
89 if is_int then return to_i
90 return to_f
91 end
92
93 # Is this value a boolean?
94 #
95 # assert "true".to_json_value.is_bool
96 # assert "false".to_json_value.is_bool
97 fun is_bool: Bool do return value isa Bool
98
99 # Get this value as a `Bool`
100 #
101 # require: `self.is_bool`
102 #
103 # assert "true".to_json_value.to_bool
104 # assert not "false".to_json_value.to_bool
105 fun to_bool: Bool do return value.as(Bool)
106
107 # Is this value a string?
108 #
109 # assert "\"str\"".to_json_value.is_string
110 # assert not "123".to_json_value.is_string
111 fun is_string: Bool do return value isa String
112
113 # Get this value as a `String`
114 #
115 # If value is null, return "null", otherwise returns `value.to_s`. It is practical
116 # on most types, except maps which does not have a custom `to_s`.
117 #
118 # assert "\"str\"".to_json_value.to_s == "str"
119 # assert "123".to_json_value.to_s == "123"
120 # assert "true".to_json_value.to_s == "true"
121 # assert "[1, 2, 3]".to_json_value.to_s == "123"
122 redef fun to_s: String
123 do
124 if value == null then return "null"
125 return value.to_s
126 end
127
128 ### Objects
129
130 # Is this value a Json object (a map)?
131 #
132 # assert """{"a": 123}""".to_json_value.is_map
133 # assert not "123".to_json_value.is_map
134 fun is_map: Bool do return value isa MapRead[String, nullable Object]
135
136 # Get this value as a `Map[String, JsonValue]`
137 #
138 # require: `self.is_map`
139 fun to_map: Map[String, JsonValue] do
140 var value = value
141 assert value isa MapRead[String, nullable Object]
142
143 var map = new HashMap[String, JsonValue]
144 for k, v in value do map[k] = new JsonValue(v)
145 return map
146 end
147
148 ### Arrays
149
150 # Is this value an array?
151 #
152 # assert "[]".to_json_value.is_array
153 # assert "[1, 2, 3, 4, 5]".to_json_value.is_array
154 # assert "[null, true, false, 0.0, 1, \"str\"]".to_json_value.is_array
155 # assert """["a", "b", "c"]""".to_json_value.is_array
156 fun is_array: Bool do return value isa SequenceRead[nullable Object]
157
158 # Get this value as an `Array[JsonValue]`
159 #
160 # require: `self.is_array`
161 #
162 # assert """["a", "b", "c"]""".to_json_value.to_a.join(", ") == "a, b, c"
163 fun to_a: Array[JsonValue]
164 do
165 var value = value
166 assert value isa SequenceRead[nullable Object]
167
168 var a = new Array[JsonValue]
169 for e in value do a.add(new JsonValue(e))
170 return a
171 end
172
173 ### Error
174
175 # Is this value an error?
176 #
177 # assert "[]".to_json_value[0].is_error
178 # assert "[".to_json_value.is_error
179 # assert not "[]".to_json_value.is_error
180 fun is_error: Bool do return value isa Error
181
182 # Get this value as a `Error`.
183 #
184 # require: `self.is_error`
185 fun to_error: Error do return value.as(Error)
186
187 ### JsonParseError
188
189 # Is this value a parse error?
190 #
191 # assert "[".to_json_value.is_parse_error
192 # assert not "[]".to_json_value.is_parse_error
193 fun is_parse_error: Bool do return value isa JsonParseError
194
195 # Get this value as a `JsonParseError`.
196 #
197 # require: `self.is_parse_error`
198 fun to_parse_error: JsonParseError do return value.as(JsonParseError)
199
200 ### Children access
201
202 # Iterator over the values of the array `self`
203 #
204 # require: `self.is_array`
205 #
206 # var a = new Array[String]
207 # for e in """["a", "b", "c"]""".to_json_value do a.add(e.to_s)
208 # assert a[0] == "a"
209 # assert a[1] == "b"
210 # assert a[2] == "c"
211 fun iterator: Iterator[JsonValue] do return to_a.iterator
212
213 # Get value at index `key` on the array or map `self`
214 #
215 # require: `self.is_array or self.is_map`
216 # require: `self.is_array implies key isa Int`
217 #
218 # assert """{"a": 123}""".to_json_value["a"].to_i == 123
219 # assert """{"123": "a"}""".to_json_value[123].to_s == "a"
220 # assert """{"John Smith": 1980}""".to_json_value[["John ", "Smith"]].to_i == 1980
221 # assert """{"a": 123}""".to_json_value["b"].is_error
222 #
223 # assert """["a", "b", "c"]""".to_json_value[0].to_s == "a"
224 # assert """["a", "b", "c"]""".to_json_value[3].is_error
225 fun [](key: Object): JsonValue do
226 var value = value
227 var result: nullable Object
228 if is_error then
229 return self
230 else if value isa MapRead[String, nullable Object] then
231 key = key.to_s
232 if value.has_key(key) then
233 result = value[key]
234 else
235 result = new JsonKeyError("Key `{key}` not found.", self, key)
236 end
237 else if value isa SequenceRead[nullable Object] then
238 if key isa Int then
239 if key < value.length and key >= 0 then
240 result = value[key]
241 else
242 result = new JsonKeyError("Index `{key}` out of bounds.",
243 self, key)
244 end
245 else
246 result = new JsonKeyError("Invalid key type. Expecting `Int`. Got `{key.class_name}`.",
247 self, key)
248 end
249 else
250 result = new JsonKeyError("Invalid `[]` access on a `{json_type}` JsonValue.",
251 self, key)
252 end
253 return new JsonValue(result)
254 end
255
256 # Advanced query to get a value within the map `self` or it's children.
257 #
258 # A query is composed of the keys to each map seperated by '.'.
259 #
260 # require: `self.is_map`
261 #
262 # assert """{"a": {"t": true, "f": false}}""".to_json_value.get("a").is_map
263 # assert """{"a": {"t": true, "f": false}}""".to_json_value.get("a.t").to_bool
264 # assert not """{"a": {"t": true, "f": false}}""".to_json_value.get("a.f").to_bool
265 # assert """{"a": {"t": true, "f": false}}""".to_json_value.get("a.t.t").is_error
266 # assert """{"a": {"b": {"c": {"d": 123}}}}""".to_json_value.get("a.b.c.d").to_i == 123
267 # assert """{"a": {"b": {"c": {"d": 123}}}}""".to_json_value.get("a.z.c.d").is_error
268 fun get(query: String): JsonValue do
269 var keys = query.split(".")
270 var value = value
271 if is_error then return self
272 for i in [0..keys.length[ do
273 var key = keys[i]
274 if value isa MapRead[String, nullable Object] then
275 if value.has_key(key) then
276 value = value[key]
277 else
278 var sub_query = sub_query_to_s(keys, i)
279 var e = new JsonKeyError("Key `{key}` not found.",
280 self, sub_query)
281 return new JsonValue(e)
282 end
283 else
284 var sub_query = sub_query_to_s(keys, i)
285 var val_type = (new JsonValue(value)).json_type
286 var e = new JsonKeyError("Value at `{sub_query}` is not a map. Got type `{val_type}`",
287 self, sub_query)
288 return new JsonValue(e)
289 end
290 end
291 return new JsonValue(value)
292 end
293
294 # Concatenate all keys up to `last` for debugging purposes.
295 #
296 # Note: This method deletes elements in `keys`.
297 private fun sub_query_to_s(keys: Array[String], last: Int): String do
298 last += 1
299 for j in [last..keys.length[ do keys.pop
300 return keys.join(".")
301 end
302
303 # Return a human-readable description of the type.
304 #
305 # For debugging purpose only.
306 fun json_type: String do
307 if is_array then return "array"
308 if is_bool then return "bool"
309 if is_float then return "float"
310 if is_int then return "int"
311 if is_null then return "null"
312 if is_map then return "map"
313 if is_string then return "string"
314 if is_parse_error then return "parse_error"
315 if is_error then return "error"
316 return "undefined"
317 end
318 end
319
320 # Keyed access failed.
321 class JsonKeyError
322 super Error
323
324 # The value on which the access was requested.
325 var json_value: JsonValue
326
327 # The requested key.
328 #
329 # In the case of `JsonValue.get`, the sub-query that failed.
330 var key: Object
331 end
332
333 redef class Text
334 # Parse `self` to obtain a `JsonValue`
335 fun to_json_value: JsonValue do
336 var value = parse_json
337 return new JsonValue(value)
338 end
339 end