Last active
March 15, 2019 11:57
-
-
Save backslash-f/6276ffd46095cb3f5341ad6520d5b32d to your computer and use it in GitHub Desktop.
Primitive example on how to manually parse a JSON in Swift
This file contains hidden or 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
#!/usr/bin/swift | |
import Foundation | |
let jsonData = Data(""" | |
{ | |
"premiumBundle": { | |
"enabled": true, | |
"variations": { | |
"sku1": { | |
"savings": "60%", | |
"sku": "US-PBT0-5-2-1" | |
}, | |
"sku2": { | |
"savings": "70%", | |
"sku": "US-PBT1-5-2-1" | |
}, | |
"sku3": { | |
"savings": "80%", | |
"sku": "US-PBT2-5-2-1" | |
}, | |
"sku4": { | |
"savings": "90%", | |
"sku": "US-PBT3-5-2-1" | |
} | |
} | |
} | |
} | |
""".utf8) | |
do { | |
if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: AnyObject] { | |
if let premiumBundle = json["premiumBundle"] as? [String: AnyObject] { | |
if let variations = premiumBundle["variations"] as? [String: [String: AnyObject]] { | |
if let sku3Variation = variations["sku3"] { | |
// SKU | |
if let sku = sku3Variation["sku"] as? String { | |
print(sku) | |
} | |
// SAVINGS | |
if let savings = sku3Variation["savings"] as? String { | |
print(savings) | |
} | |
} | |
} | |
} | |
} | |
} catch { | |
print(error) | |
} | |
/// Prints: | |
/// US-PBT2-5-2-1 | |
/// 80% |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment