Advertisement
Larme

Untitled

Mar 2nd, 2021
943
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.83 KB | None | 0 0
  1. func firstItem() {
  2.     let initialJSONString = """
  3. [{"k": "a"}, {"h": "b"}]
  4. """
  5.  
  6.     let initialJSONData = initialJSONString.data(using: .utf8)!
  7.     do {
  8.         guard let jsonArray = try JSONSerialization.jsonObject(with: initialJSONData) as? [[String: Any]] else {
  9.             print("Initial JSON wasn't an array of dictionaries with strings keys ([[String: Any]]) at top level"); return
  10.         }
  11.         guard let firstDictionary = jsonArray.first else { print("JSON Array was empty"); return }
  12.         let firstDictionaryAsJSONData = try JSONSerialization.data(withJSONObject: firstDictionary, options: .prettyPrinted)
  13.         let firstDictionaryAsJSONString = String(data: firstDictionaryAsJSONData, encoding: .utf8)!
  14.         print("Output:\n\(firstDictionaryAsJSONString)")
  15.     } catch {
  16.         print("Error: \(error)")
  17.     }
  18. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement