Skip to content

Instantly share code, notes, and snippets.

@priore
Last active November 25, 2022 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save priore/82c5848b7a70a1525854d8aba8cfc699 to your computer and use it in GitHub Desktop.
Save priore/82c5848b7a70a1525854d8aba8cfc699 to your computer and use it in GitHub Desktop.
Take an element of the json by key/value and in any position it is
public extension String {
/// Search a json key/value and return the relative full json object
func searchAndDecode<T: Codable>(key: String?, value: String?) -> [T]? {
guard let key, let value else { return nil }
let pattern = "\\{[^}]*?\"\(key)\".*\"\(value)\"[^}]*\\}"
guard let list = self.replacingOccurrences(of: "{", with: "{\n").capture(pattern: pattern),
let data = "[\(list.joined(separator: ","))]".data(using: .utf8),
let items = try? JSONDecoder().decode([T].self, from: data)
else { return nil }
return items
}
/// Capture multiple values using regular expressions
func capture(pattern: String) -> [String]? {
guard let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) else { return nil }
let matchs = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.count))
return matchs.map({
match in (0..<match.numberOfRanges).map({
return (self as NSString).substring(with: match.range(at: $0))
})
}).reduce([], +)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment