How to read a JSON file from your bundle and output the contents as a String in Swift

When you’re first getting started with Swift, even the easiest things may seem a challenge. For example, reading in a JSON file, converting its contents to a String and then sending the result to the console may take a while to figure out (at least, it did for me…).

I needed to do this in my current project for diagnostic purposes, and thought it might be helpful to others, so here’s the little code snippet I used:

    // 1
    let filePath = NSBundle.mainBundle().pathForResource("MyJSONFileName",ofType:"json")
    // 2
    var readError:NSError?
    // 3
    if let data = NSData(contentsOfFile:filePath!, options:NSDataReadingOptions.DataReadingUncached, error:&readError) {
        // 4
        let stringData = NSString(data: data, encoding: NSUTF8StringEncoding)
        // 5
        println("data read: \(stringData)")

As you can see, it’s pretty straightforward.

  1. Create a file path to the file.
  2. Declare an NSError object for use in the reading (this example just eats the error, however).
  3. Read in the data from the JSON file.
  4. Create an NString object, initializing it with the NSString(data:encoding:) method.
  5. Output the result.