X-Git-Url: http://nitlanguage.org diff --git a/lib/json/dynamic.nit b/lib/json/dynamic.nit index 2f73fea..55821ef 100644 --- a/lib/json/dynamic.nit +++ b/lib/json/dynamic.nit @@ -14,16 +14,24 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Dynamic interface to read Json strings. +# Dynamic interface to read JSON strings. # # `String::to_json_value` returns a `JsonValue` which can be queried -# to get the underlying Json data. It can also be used as any Json types. +# to get the underlying JSON data. module dynamic import error private import static +# Wraps a JSON value. +# +# Offer methods to query the type, to dynamicaly cast the underlying value and +# to query elements (in case of a JSON object or a JSON array). +# +# Use `String::to_json_value` to get a `JsonValue` from a string. class JsonValue + + # The wrapped JSON value. var value: nullable Object # Is this value null? @@ -41,11 +49,17 @@ class JsonValue # Get this value as a `Int` # - # require: `self.is_int` + # require: `self.is_numeric` # # assert "-10".to_json_value.to_i == -10 # assert "123".to_json_value.to_i == 123 - fun to_i: Int do return value.as(Int) + # assert "123.456".to_json_value.to_i == 123 + fun to_i: Int + do + var value = value + assert value isa Numeric + return value.to_i + end # Is this value a float? # @@ -56,11 +70,17 @@ class JsonValue # Get this value as a `Float` # - # require: `self.is_float` + # require: `self.is_numeric` # # assert "0.0".to_json_value.to_f == 0.0 # assert "123.456".to_json_value.to_f == 123.456 - fun to_f: Float do return value.as(Float) + # assert "123".to_json_value.to_f == 123.0 + fun to_f: Float + do + var value = value + assert value isa Numeric + return value.to_f + end # Is the value numeric? # @@ -110,9 +130,8 @@ class JsonValue # assert "\"str\"".to_json_value.to_s == "str" # assert "123".to_json_value.to_s == "123" # assert "true".to_json_value.to_s == "true" - # assert "[1, 2, 3]".to_json_value.to_s == "123" - redef fun to_s: String - do + # assert "[1, 2, 3]".to_json_value.to_s == "[1,2,3]" + redef fun to_s do if value == null then return "null" return value.to_s end @@ -209,7 +228,7 @@ class JsonValue # # assert """{"a": 123}""".to_json_value["a"].to_i == 123 # assert """{"123": "a"}""".to_json_value[123].to_s == "a" - # assert """{"John Smith": 1980}""".to_json_value[["John ", "Smith"]].to_i == 1980 + # assert """{"John Smith": 1980}""".to_json_value["John Smith"].to_i == 1980 # assert """{"a": 123}""".to_json_value["b"].is_error # # assert """["a", "b", "c"]""".to_json_value[0].to_s == "a"