Last active
November 25, 2022 18:01
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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