Saturday, September 12, 2015

Print out JSON content in Swift playground

Update - May 19, 2017 Swift 3.1 (Xcode 8.3.2)
Original post - September 12, 2015 Swift 1.2 (Xcode 6.4).

1. In the playground, press 'command ⌘' + 1 to show the project navigator.
You may also do this by selecting
View -> Navigators -> Show Project Navigator.




To hide the project navigator later, press 'command ⌘' + 0.

2. Add a new file called json.txt to the Resources folder.



3.  Edit json.txt as:


{"result":{"information":[{"name":"Tom","age":25},{"name":"Andy","age":30},{"name":"Peter","age":35},{"name":"David","age":40}]}}

4.  Edit the playground as:

Update - May 19, 2017 Swift 3.1 (Xcode 8.3.2)

import UIKit

let bundle = Bundle.main
let path = bundle.path(forResource: "json", ofType: "txt")

let jsonString = try NSString(contentsOfFile: path!, encoding: String.Encoding.utf8.rawValue)

print(jsonString)

let data = jsonString.data(using: String.Encoding.utf8.rawValue)!

let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String: Any]

print(json!)

let result = json?["result"] as? [String: Any]
let information = result?["information"] as? [[String: Any]]
let item = information?[0]
let name = item?["name"]
let age = item?["age"]
print(name!)
print(age!)

var array : [String] = []

for loopitem in information! {
    
    let myName = loopitem["name"]
    let myAge = loopitem["age"]
    print("name: \(myName!) age: \(myAge!)")
    array.append(String(stringInterpolationSegment: myName!))
}
for element in array {
    print("element: \(element)")
}

Original Post: September 12, 2015 with Swift 1.2 (Xcode 6.4).

import UIKit

let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("json", ofType: "txt")
let jsonString = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)!
println(jsonString)

var data : NSData! = jsonString.dataUsingEncoding(NSUTF8StringEncoding)

let json:AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:nil)
println(json)

let result: AnyObject? = json["result"]
let information: AnyObject? = result?["information"]
let item : AnyObject? = information?[0]
let name: AnyObject? = item?["name"]
let age: AnyObject? = item?["age"]
println(name!)
println(age!)

var array : [String] = []

for loopitem in result?["information"] as! NSArray {
    
    let myName: AnyObject? = loopitem["name"]
    let myAge: AnyObject? = loopitem["age"]
    println("name: \(myName!) age: \(myAge!)")
    array.append(String(stringInterpolationSegment: myName!))
}
for element in array {
    println("element: \(element)")
}

5. The result is:



Related Information:

JavaScript and JSON

No comments:

Post a Comment