key
on the array or map self
require: self.is_array or self.is_map
require: self.is_array implies key isa Int
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 """{"a": 123}""".to_json_value["b"].is_error
assert """["a", "b", "c"]""".to_json_value[0].to_s == "a"
assert """["a", "b", "c"]""".to_json_value[3].is_error
# Get value at index `key` on the array or map `self`
#
# require: `self.is_array or self.is_map`
# require: `self.is_array implies key isa Int`
#
# 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 """{"a": 123}""".to_json_value["b"].is_error
#
# assert """["a", "b", "c"]""".to_json_value[0].to_s == "a"
# assert """["a", "b", "c"]""".to_json_value[3].is_error
fun [](key: Object): JsonValue do
var value = value
var result: nullable Object
if is_error then
return self
else if value isa MapRead[String, nullable Object] then
key = key.to_s
if value.has_key(key) then
result = value[key]
else
result = new JsonKeyError("Key `{key}` not found.", self, key)
end
else if value isa SequenceRead[nullable Object] then
if key isa Int then
if key < value.length and key >= 0 then
result = value[key]
else
result = new JsonKeyError("Index `{key}` out of bounds.",
self, key)
end
else
result = new JsonKeyError("Invalid key type. Expecting `Int`. Got `{key.class_name}`.",
self, key)
end
else
result = new JsonKeyError("Invalid `[]` access on a `{json_type}` JsonValue.",
self, key)
end
return new JsonValue(result)
end
lib/json/dynamic.nit:243,2--284,4