Once you query a JSON value using one of the higher order selectors, the resulting type of the expression will be a lazy RBBJSONQuery:
json.store.book[0]["title"] // RBBJSON.string("Sayings of the Century")
json.store.book[0, 1]["title"] // some RBBJSONQuery
Because RBBJSONQuery conforms to Sequence, you can initialize an Array with it to obtain the results or use e.g. compactMap:
String(json.store.book[0].title) // "Sayings of the Century"
json.store.book[0, 1].title.compactMap(String.init) // ["Sayings of the Century", "Sword of Honour"]
String(json.store.book[0]["invalid Property"]) // nil
json.store.book[0, 1]["invalid Property"].compactMap(String.init) // []
RBBJSON
RBBJSON enables flexible JSON traversal at runtime and JSONPath-like querying for rapid prototyping.
Use
JSONDecoderto create anRBBJSONstruct, then traverse it using dynamic member lookup:If you want to access a value that coincides with a Swift-defined property, use a
Stringsubscript instead:To unbox a JSON value, use one of the failable initializers:
You can also make use of a JSONPath-inspired Query syntax to find nested data inside a JSON structure.
For example, given:
$.store.book[*].authorjson.store.book[any: .child].author$..authorjson[any: .descendantOrSelf].author$.store.*json.store[any: .child]$.store..pricejson.store[any: .descendantOrSelf].price$..book[2]json[any: .descendantOrSelf].book[2]$..book[-2]json[any: .descendantOrSelf].book[-2]$..book[0,1],$..book[:2]json[any: .descendantOrSelf].book[0, 1]),json[any: .descendantOrSelf].book[0...1]),json[any: .descendantOrSelf].book[0..<2])$..book[?(@.isbn)]json[any: .descendantOrSelf].book[has: \.isbn]$..book[?(@.price<10)]json.store.book[matches: { $0.price <= 10 }]10.$.store["book", "bicycle"]..["price", "author"]json.store["book", "bicycle"][any: .descendantOrSelf]["price", "author"]Once you query a JSON value using one of the higher order selectors, the resulting type of the expression will be a lazy
RBBJSONQuery:Because
RBBJSONQueryconforms toSequence, you can initialize anArraywith it to obtain the results or use e.g.compactMap: