JSON parser in Swift for easy access to JSON data
JSONParser is a simple light-weight parser that helps retrieve the data you want from a JSON data. This is achieve by applying syntactic sugar to on the Collection Objects extracted from the JSON data. I hope this readme will be as lightweight as this entire project. It works well with both network data calls as well as reading from a local json file.
Requirements: Xcode 6.1 and iOS 7.0 or above
Just save JSONParser.swift and drop it into your xcode project.
>>>
is the main infix operator that is used throughout the reading of the JSON Data. It returns an Optional AnyObject. If there is any error, it will return nil.
Contents of jsonDict.json
{
"Some Key":"Hi there. I'm stored in some key"
}
To extract out the data,
let path = NSBundle.mainBundle().pathForResource("jsonDict", ofType:"json")
let data = NSData(contentsOfFile:path!)
let someKeyData: NSString? = (data >>> "Some Key") as? NSString
println(someKeyData) //This will print Optional(Hi there. I'm stored in some key)
- Use it to extract data from dictionary directly from NSData object (as shown in example above)
- Use it to extract data from array directly from NSData object
Contents of jsonArr.json:
[
"Item 0",
"Item 1",
"Item 2"
]
To extract out the data,
let path = NSBundle.mainBundle().pathForResource("jsonArr", ofType:"json")
let data = NSData(contentsOfFile:path!)
let someKeyData: NSString? = (data >>> 1) as? NSString
println(someKeyData) //This will print Optional(Item 1)
- Use it to extract arrays or dictionaries from other arrays or dictionaries, in a chain
Contents of jsonMix.json: (example from http://json.org/example)
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
let path = NSBundle.mainBundle().pathForResource("jsonMix", ofType:"json")
let data = NSData(contentsOfFile:path!)
let someKeyData:AnyObject? = data >>> "glossary" >>> "GlossDiv" >>> "GlossList" >>> "GlossEntry" >>> "GlossDef" >>> "GlossSeeAlso" >>> 0
println(someKeyData as? NSString) //This will print Optional(GML)