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
JSONDecoder
to create anRBBJSON
struct, then traverse it using dynamic member lookup:If you want to access a value that coincides with a Swift-defined property, use a
String
subscript 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[*].author
json.store.book[any: .child].author
$..author
json[any: .descendantOrSelf].author
$.store.*
json.store[any: .child]
$.store..price
json.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
RBBJSONQuery
conforms toSequence
, you can initialize anArray
with it to obtain the results or use e.g.compactMap
: