JSONPath is simple library for parsing complicate JSON structures
Swift 4.2
JSONPath is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'JSONPath'Let’s we have the struct:
struct Person: Codable {
let name: String
let age: Int
}and the JSON:
{
"payload": {
"persons": [
{
"name": "Ed",
"age": "39"
},
{
"name": "Keily",
"age": "37"
}
]
}
}There are few ways to got the struct from the JSON
- Refuse
Codableand parse it with any of 3rd party parsing library manually - Use
Codablebut create 2 extra structs. Or 1 extra struct with custom init - Using JSONPath simple call through JSON path and get array of Codable persons
The base struct of the library is JSONTree. Objects of this type are initialized with JSON Data.
let json = [
"payload": [
"persons": [
[
"name": "Ed",
"age": "39"
],
[
"name": "Keily",
"age": "37"
]
]
]
]
let jsonData = try JSONSerialization.data(withJSONObject: json, options: [])
let jsonTree = try JSONTree(data: jsonData)It supports dynamicMemberLookup . To parse array of Person :
let persons: [Person]? = tree.payload?.persons?.value()And you can subscribe by index:
let person: Person? = tree.payload?.persons?[0]?.value()If you want to help improve this library you can take on of the opened tasks:
- Setup Travis CI
- Exceptions instead of Optional result
- Carthage support
Bogdan Manshilin, skimphiter@gmail.com
JSONPath is available under the MIT license. See the LICENSE file for more info.