lib/json: converting JsonValue to float or int casts between numerics
[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_numeric`
53 #
54 # assert "-10".to_json_value.to_i == -10
55 # assert "123".to_json_value.to_i == 123
56 # assert "123.456".to_json_value.to_i == 123
57 fun to_i: Int
58 do
59 var value = value
60 assert value isa Numeric
61 return value.to_i
62 end
63
64 # Is this value a float?
65 #
66 # assert "0.0".to_json_value.is_float
67 # assert "123.456".to_json_value.is_float
68 # assert not "123".to_json_value.is_float
69 fun is_float: Bool do return value isa Float
70
71 # Get this value as a `Float`
72 #
73 # require: `self.is_numeric`
74 #
75 # assert "0.0".to_json_value.to_f == 0.0
76 # assert "123.456".to_json_value.to_f == 123.456
77 # assert "123".to_json_value.to_f == 123.0
78 fun to_f: Float
79 do
80 var value = value
81 assert value isa Numeric
82 return value.to_f
83 end
84
85 # Is the value numeric?
86 #
87 # assert "1.234".to_json_value.is_numeric
88 # assert "1234".to_json_value.is_numeric
89 # assert not "\"str\"".to_json_value.is_numeric
90 # assert not "1.2.3.4".to_json_value.is_numeric
91 fun is_numeric: Bool do return is_int or is_float
92
93 # Get this value as a `Numeric`
94 #
95 # require: `self.is_numeric`
96 #
97 # assert "1.234".to_json_value.to_numeric == 1.234
98 # assert "1234".to_json_value.to_numeric == 1234
99 fun to_numeric: Numeric
100 do
101 if is_int then return to_i
102 return to_f
103 end
104
105 # Is this value a boolean?
106 #
107 # assert "true".to_json_value.is_bool
108 # assert "false".to_json_value.is_bool
109 fun is_bool: Bool do return value isa Bool
110
111 # Get this value as a `Bool`
112 #
113 # require: `self.is_bool`
114 #
115 # assert "true".to_json_value.to_bool
116 # assert not "false".to_json_value.to_bool
117 fun to_bool: Bool do return value.as(Bool)
118
119 # Is this value a string?
120 #
121 # assert "\"str\"".to_json_value.is_string
122 # assert not "123".to_json_value.is_string
123 fun is_string: Bool do return value isa String
124
125 # Get this value as a `String`
126 #
127 # If value is null, return "null", otherwise returns `value.to_s`. It is practical
128 # on most types, except maps which does not have a custom `to_s`.
129 #
130 # assert "\"str\"".to_json_value.to_s == "str"
131 # assert "123".to_json_value.to_s == "123"
132 # assert "true".to_json_value.to_s == "true"
133 # assert "[1, 2, 3]".to_json_value.to_s == "123"
134 redef fun to_s: String
135 do
136 if value == null then return "null"
137 return value.to_s
138 end
139
140 ### Objects
141
142 # Is this value a Json object (a map)?
143 #
144 # assert """{"a": 123}""".to_json_value.is_map
145 # assert not "123".to_json_value.is_map
146 fun is_map: Bool do return value isa MapRead[String, nullable Object]
147
148 # Get this value as a `Map[String, JsonValue]`
149 #
150 # require: `self.is_map`
151 fun to_map: Map[String, JsonValue] do
152 var value = value
153 assert value isa MapRead[String, nullable Object]
154
155 var map = new HashMap[String, JsonValue]
156 for k, v in value do map[k] = new JsonValue(v)
157 return map
158 end
159
160 ### Arrays
161
162 # Is this value an array?
163 #
164 # assert "[]".to_json_value.is_array
165 # assert "[1, 2, 3, 4, 5]".to_json_value.is_array
166 # assert "[null, true, false, 0.0, 1, \"str\"]".to_json_value.is_array
167 # assert """["a", "b", "c"]""".to_json_value.is_array
168 fun is_array: Bool do return value isa SequenceRead[nullable Object]
169
170 # Get this value as an `Array[JsonValue]`
171 #
172 # require: `self.is_array`
173 #
174 # assert """["a", "b", "c"]""".to_json_value.to_a.join(", ") == "a, b, c"
175 fun to_a: Array[JsonValue]
176 do
177 var value = value
178 assert value isa SequenceRead[nullable Object]
179
180 var a = new Array[JsonValue]
181 for e in value do a.add(new JsonValue(e))
182 return a
183 end
184
185 ### Error
186
187 # Is this value an error?
188 #
189 # assert "[]".to_json_value[0].is_error
190 # assert "[".to_json_value.is_error
191 # assert not "[]".to_json_value.is_error
192 fun is_error: Bool do return value isa Error
193
194 # Get this value as a `Error`.
195 #
196 # require: `self.is_error`
197 fun to_error: Error do return value.as(Error)
198
199 ### JsonParseError
200
201 # Is this value a parse error?
202 #
203 # assert "[".to_json_value.is_parse_error
204 # assert not "[]".to_json_value.is_parse_error
205 fun is_parse_error: Bool do return value isa JsonParseError
206
207 # Get this value as a `JsonParseError`.
208 #
209 # require: `self.is_parse_error`
210 fun to_parse_error: JsonParseError do return value.as(JsonParseError)
211
212 ### Children access
213
214 # Iterator over the values of the array `self`
215 #
216 # require: `self.is_array`
217 #
218 # var a = new Array[String]
219 # for e in """["a", "b", "c"]""".to_json_value do a.add(e.to_s)
220 # assert a[0] == "a"
221 # assert a[1] == "b"
222 # assert a[2] == "c"
223 fun iterator: Iterator[JsonValue] do return to_a.iterator
224
225 # Get value at index `key` on the array or map `self`
226 #
227 # require: `self.is_array or self.is_map`
228 # require: `self.is_array implies key isa Int`
229 #
230 # assert """{"a": 123}""".to_json_value["a"].to_i == 123
231 # assert """{"123": "a"}""".to_json_value[123].to_s == "a"
232 # assert """{"John Smith": 1980}""".to_json_value[["John ", "Smith"]].to_i == 1980
233 # assert """{"a": 123}""".to_json_value["b"].is_error
234 #
235 # assert """["a", "b", "c"]""".to_json_value[0].to_s == "a"
236 # assert """["a", "b", "c"]""".to_json_value[3].is_error
237 fun [](key: Object): JsonValue do
238 var value = value
239 var result: nullable Object
240 if is_error then
241 return self
242 else if value isa MapRead[String, nullable Object] then
243 key = key.to_s
244 if value.has_key(key) then
245 result = value[key]
246 else
247 result = new JsonKeyError("Key `{key}` not found.", self, key)
248 end
249 else if value isa SequenceRead[nullable Object] then
250 if key isa Int then
251 if key < value.length and key >= 0 then
252 result = value[key]
253 else
254 result = new JsonKeyError("Index `{key}` out of bounds.",
255 self, key)
256 end
257 else
258 result = new JsonKeyError("Invalid key type. Expecting `Int`. Got `{key.class_name}`.",
259 self, key)
260 end
261 else
262 result = new JsonKeyError("Invalid `[]` access on a `{json_type}` JsonValue.",
263 self, key)
264 end
265 return new JsonValue(result)
266 end
267
268 # Advanced query to get a value within the map `self` or it's children.
269 #
270 # A query is composed of the keys to each map seperated by '.'.
271 #
272 # require: `self.is_map`
273 #
274 # assert """{"a": {"t": true, "f": false}}""".to_json_value.get("a").is_map
275 # assert """{"a": {"t": true, "f": false}}""".to_json_value.get("a.t").to_bool
276 # assert not """{"a": {"t": true, "f": false}}""".to_json_value.get("a.f").to_bool
277 # assert """{"a": {"t": true, "f": false}}""".to_json_value.get("a.t.t").is_error
278 # assert """{"a": {"b": {"c": {"d": 123}}}}""".to_json_value.get("a.b.c.d").to_i == 123
279 # assert """{"a": {"b": {"c": {"d": 123}}}}""".to_json_value.get("a.z.c.d").is_error
280 fun get(query: String): JsonValue do
281 var keys = query.split(".")
282 var value = value
283 if is_error then return self
284 for i in [0..keys.length[ do
285 var key = keys[i]
286 if value isa MapRead[String, nullable Object] then
287 if value.has_key(key) then
288 value = value[key]
289 else
290 var sub_query = sub_query_to_s(keys, i)
291 var e = new JsonKeyError("Key `{key}` not found.",
292 self, sub_query)
293 return new JsonValue(e)
294 end
295 else
296 var sub_query = sub_query_to_s(keys, i)
297 var val_type = (new JsonValue(value)).json_type
298 var e = new JsonKeyError("Value at `{sub_query}` is not a map. Got type `{val_type}`",
299 self, sub_query)
300 return new JsonValue(e)
301 end
302 end
303 return new JsonValue(value)
304 end
305
306 # Concatenate all keys up to `last` for debugging purposes.
307 #
308 # Note: This method deletes elements in `keys`.
309 private fun sub_query_to_s(keys: Array[String], last: Int): String do
310 last += 1
311 for j in [last..keys.length[ do keys.pop
312 return keys.join(".")
313 end
314
315 # Return a human-readable description of the type.
316 #
317 # For debugging purpose only.
318 fun json_type: String do
319 if is_array then return "array"
320 if is_bool then return "bool"
321 if is_float then return "float"
322 if is_int then return "int"
323 if is_null then return "null"
324 if is_map then return "map"
325 if is_string then return "string"
326 if is_parse_error then return "parse_error"
327 if is_error then return "error"
328 return "undefined"
329 end
330 end
331
332 # Keyed access failed.
333 class JsonKeyError
334 super Error
335
336 # The value on which the access was requested.
337 var json_value: JsonValue
338
339 # The requested key.
340 #
341 # In the case of `JsonValue.get`, the sub-query that failed.
342 var key: Object
343 end
344
345 redef class Text
346 # Parse `self` to obtain a `JsonValue`
347 fun to_json_value: JsonValue do
348 var value = parse_json
349 return new JsonValue(value)
350 end
351 end