Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- func firstItem() {
- let initialJSONString = """
- [{"k": "a"}, {"h": "b"}]
- """
- let initialJSONData = initialJSONString.data(using: .utf8)!
- do {
- guard let jsonArray = try JSONSerialization.jsonObject(with: initialJSONData) as? [[String: Any]] else {
- print("Initial JSON wasn't an array of dictionaries with strings keys ([[String: Any]]) at top level"); return
- }
- guard let firstDictionary = jsonArray.first else { print("JSON Array was empty"); return }
- let firstDictionaryAsJSONData = try JSONSerialization.data(withJSONObject: firstDictionary, options: .prettyPrinted)
- let firstDictionaryAsJSONString = String(data: firstDictionaryAsJSONData, encoding: .utf8)!
- print("Output:\n\(firstDictionaryAsJSONString)")
- } catch {
- print("Error: \(error)")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement