getByPath function
tries to follow a given path
in a json
mapping
e.g.
var json = {'test': [2, {'hallo': 'welt'}]};
var path = ['test', 1, 'hallo'];
var result = getByPath(json, path);
# result == 'welt';
if [path] is empty, the [json] is returned as is
will raise a [JsonPathNotFoundException] if the path is not found
Implementation
dynamic getByPath(Json json, SimpleJsonPath path) {
if (path.isEmpty) {
return json;
}
SimpleJsonPath currentPath = [];
dynamic current = json;
// iterate over each part segment
for (var part in path) {
currentPath.add(part);
if (part.runtimeType == int) {
if (current.runtimeType != List) {
throw JsonPathException(
'Element `${currentPath.prettyPrint()}` is not a list, '
'but a `${current.runtimeType}`.', code: 234839405);
}
current = current[part];
} else if (part.runtimeType == String) {
// check if the thing is map-able
// note that jsonDecode returns a _InternalLinkedHashMap
// which for whatever reason is not a Map, so we cannot just check it
if (current.containsKey(part)) {
current = current[part];
} else {
throw JsonPathException(
'Element `${currentPath.prettyPrint()}` was not found', code: 429348534);
}
} else { // invalid path segment
throw JsonPathException('Path at ${currentPath.prettyPrint()} '
'is not a valid path. '
'Only String and Integer elements are allowed.', code: 4583904);
}
}
return current;
}