How to retrieve data from file with SwiftyJSON
Asked Answered
R

3

9

I have added a JSON-file to my file-system where the data is structured like this:

{ "DDD" : "3D Systems Corporation", "MMM" : "3M Company", "WBAI" : "500.com Limited", "WUBA" : "58.com Inc.", "AHC" : "A.H. Belo Corporation", "ATEN" : "A10 Networks, Inc.", "AAC" : "AAC Holdings, Inc.", "AIR" : "AAR Corp." }

my file-name is stockDict.json and I'm trying to retrieve the data from it by using this code:

let jsonFilePath:NSString = NSBundle.mainBundle().pathForResource("stockDict", ofType: "json")!
        let jsonData:NSData = NSData.dataWithContentsOfMappedFile(jsonFilePath as String) as! NSData
        let error:NSError?
        let json = JSON(jsonData)

        println(json[0][0].string)

But all I get when it prints is nil. What is wrong with my code?

Any suggestions would be appreciated.

Refrain answered 28/2, 2015 at 17:2 Comment(1)
I found this answer to be very helpful https://mcmap.net/q/99358/-reading-in-a-json-file-using-swiftGrunion
G
13

Did you try with

let json = JSON(data: jsonData) // Note: data: parameter name
println(json["DDD"].string)
Graff answered 28/2, 2015 at 17:34 Comment(2)
Now I have, and it still prints "nil".Refrain
This doesn't answer the question. The question is about loading JSON from a file.Insanity
M
9

Swift 3/4 version:

let path = Bundle.main.path(forResource: "JSON", ofType: "json")!
let jsonString = try? String(contentsOfFile: path, encoding: String.Encoding.utf8)
let json = JSON(parseJSON: jsonString!)
Midshipman answered 19/9, 2017 at 10:17 Comment(1)
Nowadays it is recommended to use Bundle.main.url instead of Bundle.main.path.Alonsoalonzo
M
6

I don't have the rep to comment, but this answer is deprecated as of iOS 8, specifically the following part.

.dataWithContentsOfMappedFile

XCode is telling me.

'dataWithContentsOfMappedFile' was deprecated in iOS 8.0: Use +dataWithContentsOfURL:options:error: and NSDataReadingMappedIfSafe or NSDataReadingMappedAlways instead.

------EDIT--------

Here is the updated code I am using. It compiles and runs with a target of iOS 9.1.

let path = NSBundle.mainBundle().pathForResource("fileName", ofType: "json")
let jsonData = NSData(contentsOfFile:path!)
let json = JSON(data: jsonData!)
Mulvihill answered 13/11, 2015 at 3:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.