Skip to content

Instantly share code, notes, and snippets.

@jemmons
Created June 8, 2017 22:01
Show Gist options
  • Save jemmons/4c4bfb7feda08ecdbf74cee808a52b2c to your computer and use it in GitHub Desktop.
Save jemmons/4c4bfb7feda08ecdbf74cee808a52b2c to your computer and use it in GitHub Desktop.
Turning JSON into URLQueryParams
func f(_ jsonValue: Any, prefix: String? = nil) throws -> [URLQueryItem] {
var items: [URLQueryItem] = []
switch jsonValue {
case let d as Dictionary<String, Any>:
try d.forEach {
let newPrefix = prefix == nil ? $0.key : prefix! + "[\($0.key)]"
items.append(contentsOf: try f($0.value, prefix: newPrefix))
}
case let a as Array<Any>:
guard let somePrefix = prefix else {
throw(ParamsError.invalidTopLevelType)
}
try a.forEach { it in
items.append(contentsOf: try f(it, prefix: somePrefix + "[]"))
}
default:
guard let somePrefix = prefix else {
throw(ParamsError.invalidTopLevelType)
}
items.append(URLQueryItem(name: somePrefix, value: String(describing: jsonValue)))
}
return items
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment