How to get data from local JSON file in swift? - json

I want to get data from local JSON file. It's look like:
[
[
{
"link": "link1",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4",
"answer5"
],
"questions": "question1"
},
{
"link": "link2",
"answers": [
"answer1",
"answer2",
"answer3",
"answer4",
"answer5"
],
"questions": "question2"
}
]
]
How can I take separately each element?
And how can I take separately each answer?
I want to use answers in table view.
indexPath.row[1] = answer1
indexPath.row[2] = answer2...
let url = Bundle.main.url(forResource: "info", withExtension: "json")!
do {
let jsonData = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: jsonData)
print(json)
//let current = json["title"] as! [String: [String:Any]]
//for (key, currency) in current {
//let quest = currency["title"] as! String
//let img = currency["image"] as! String
//let ans = currency["answers"] as! [String]
//}
}
catch {
print(error)
}
}

You have to take care of the JSON structure to get the correct values. See the below snippet to see how you can reach your questions in JSON.
let url = Bundle.main.url(forResource: "File", withExtension: "txt")!
do {
let jsonData = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: jsonData) as! [[[String: Any]]]
if let question1 = json.first?[0] {
print( question1["link"] as! String)
}
if let question2 = json.first?[1] {
print( question2["link"] as! String)
}
}
catch {
print(error)
}
So now, you know how to reach the actual data. You should create some Question class. Then you should retain a list of questions parsed from the file and use that list for your TableView.

Related

Reloading new JSON data swift

I am working on a project in swift where I need to write data to a JSON file, print that data, and be able to add more data as it arrives. At the moment, I can write to the JSON and display the first inputted data but after I add more and attempt to display it again, it just prints the new data.
I am using textView to display the data and using textFields and textView to get the data.
The code below should give you a better understanding.
#IBAction func addWords(_ sender: UIButton) {
let data: [String:String] = [
"Name": nameField.text ?? "N/A",
"Definition": defView.text ?? "N/A",
"Part of Speech": posField.text ?? "N/A"
]
let fileUrl = Bundle.main.url(forResource: "data", withExtension: "json")!
if let jsonData = try? JSONSerialization.data(withJSONObject: data, options: []) {
try! jsonData.write(to: fileUrl)
nameField.text = ""
defView.text = ""
posField.text = ""
} else {
print("Failed to save")
}
}
#IBAction func loadData(_ sender: UIButton) {
let fileUrl = Bundle.main.url(forResource: "data", withExtension: "json")!
let responseData: Data? = try! Data(contentsOf: fileUrl)
if let responseData = responseData {
let json: Any? = try? JSONSerialization.jsonObject(with: responseData, options: [])
if let json = json {
let dictionary: [String: Any]? = json as? [String: Any]
if let dictionary = dictionary {
for names in dictionary {
let name: String = dictionary["Name"] as! String
let definition: String = dictionary["Definition"] as! String
let pos: String = dictionary["Part of Speech"] as! String
print(name)
textView.text = ("Name: \(name) (\(pos))\n Definition: \(definition)\n ")
}
}
}
}
}
'''

parsing YouTube json with JSONSerialization

I have trouble parsing json data from YouTube api with JSONSerialization. when I try to fetch I return error. this is my code
this is json data I want to parse, I want to get video id, url, title, and desctiption
{
"kind": "youtube#searchListResponse",
"etag": "\"j6xRRd8dTPVVptg711_CSPADRfg/mBDPbwkuU2lLUxWHYPI1X54CUwQ\"",
"nextPageToken": "CAUQAA",
"regionCode": "ID",
"pageInfo": {
"totalResults": 3552,
"resultsPerPage": 5
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "\"j6xRRd8dTPVVptg711_CSPADRfg/73cXngXOrGm_Bt7McNY945A6koc\"",
"id": {
"kind": "youtube#video",
"videoId": "-0ZZzOuuV3c"
},
"snippet": {
"publishedAt": "2018-09-20T08:00:01.000Z",
"channelId": "UCjHoMXZXAIx_QHgk9qsAJ-Q",
"title": "HADIST-HADIST PALSU TAPI POPULER - Ustadz Adi Hidayat LC MA",
"description": "\"Kebersihan sebagian dari iman\". Sering dogn mendengar ucapan ini. Sebagian orang mengatakan ini hadist dari Rasulullah. Tapi taukah kamu, bahwa ini ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/-0ZZzOuuV3c/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/-0ZZzOuuV3c/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/-0ZZzOuuV3c/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Audio Dakwah",
"liveBroadcastContent": "none"
}
}
This is my code to parse json I create it in youtubeAPI struct, when I try to run it invalidJSONData
static func videos(fromJSON data: Data) -> VideoResults {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: [])
guard
let jsonDictionary = jsonObject as? [AnyHashable: Any],
let itemsArray = jsonDictionary["items"] as? [[String: Any]]
else {
return .failure(YoutubeError.invalidJSONData)
}
var finalItems = [Video]()
for itemJSON in itemsArray {
if let item = video(fromJSON: itemJSON) {
finalItems.append(item)
}
}
if finalItems.isEmpty && !itemsArray.isEmpty {
return .failure(YoutubeError.invalidJSONData)
}
return .success(finalItems)
} catch let error {
return .failure(error)
}
}
private static func video(fromJSON json: [String: Any]) ->Video? {
guard
let videoID = json["videoID"] as? String,
let title = json["title"] as? String,
let description = json["description"] as? String,
let stringURL = json["url"] as? String,
let url = URL(string: stringURL)
else {
return nil
}
return Video(videoID: videoID, title: title, description: description, url: url)
}
with the question I have post. finally I have the answer for my problem. hopefully this will help other developer who want to parse json with JSONSerialization, with such a complex data like YouTube api or other api. so this is my answer.
Since items is an array and inside item have another nested data such as snippet, so I need to iterate snippet to get the data. This is the code.
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
var finalItems = [Video]()
if let items = jsonObject?["items"] as? Array<Dictionary<String, Any>> {
for item in items {
if
let id = item["id"] as? [String: String],
let snippet = item["snippet"] as? [String: Any] {
if
let videoID = id["videoId"],
let description = snippet["description"] as? String,
let title = snippet["title"] as? String,
let thumbnails = snippet["thumbnails"] as? [String: Any],
let medium = thumbnails["medium"] as? [String: Any],
let urlString = medium["url"] as? String,
let url = URL(string: urlString) {
finalItems.append(Video(videoID: videoID, title: title, description: description, url: url))
}
}
}
}
print(finalItems.count)
if finalItems.isEmpty {
return .failure(YoutubeError.invalidJSONData)
}
return .success(finalItems)
} catch let error {
return .failure(error)
}
And the the next step is to clean up the code for parsing that iterate the item, and put it in extension in Video Model, I was found a good article from apple developer website to clean up the code so the code not bloated in my videos function. if you are curious check out this link https://developer.apple.com/swift/blog/?id=37. so the extension for video model is like this.
extension Video {
init(dict: [String: Any]) throws {
guard
let id = dict["id"] as? [String: String],
let videoID = id["videoId"]
else {
throw SerializationError.missing("id")
}
guard
let snippet = dict["snippet"] as? [String: Any],
let description = snippet["description"] as? String,
let title = snippet["title"] as? String,
let thumbnails = snippet["thumbnails"] as? [String: Any],
let medium = thumbnails["medium"] as? [String: Any],
let urlString = medium["url"] as? String,
let url = URL(string: urlString) else { throw SerializationError.missing("snippet") }
self.videoID = videoID
self.title = title
self.description = description
self.url = url
}
}
and then update the videos function, and add do catch block when you try to append since the extension have potential error to parse json data. this is the update method
static func videos(fromJSON data: Data) -> VideoResults {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
var finalItems = [Video]()
if let items = jsonObject?["items"] as? Array<Dictionary<String, Any>> {
for item in items {
do {
try finalItems.append(Video(dict: item))
} catch let error {
print("Failed to append video: \(error)")
}
}
}
print(finalItems.count)
if finalItems.isEmpty {
return .failure(YoutubeError.invalidJSONData)
}
return .success(finalItems)
} catch let error {
return .failure(error)
}
}
and voila the code is safe now, why I not use JSONDecoder? since a lot of people recommended to use JSONDecoder. the reason is, this is my personal reason by the way other might not agree with me. I know how to use JSONDecoder but the thing is i don't want to create a lot struct to decode the json data, since with this JSONSerialization doesn't have to create struct it help me reduce a file and step up my learning curve. and hey even a library like Alamofire have a choice to parse using JSONSerialization. it's up to you now if you want to use JSONDecoder or JSONSerialization I hope this help :).

Retrieving JSON elements in Swift 3

I have following JSON file
{
"events": [
{
"date": "01/11/2017",
"name": [
"Tulsi Vivah",
"Pradosh Vrat"
],
"photo": [
"photo_chaturthi",
"photo_ekadashi"
]
},
{
"date": "03/11/2017",
"name": [
"Guru Nanak Jayanti"
],
"photo": [
"photo_chaturthi",
"photo_ekadashi"
]
}
]
}
I want to parse this and put the elements in the objectArray in the code below:
struct Objects {
var sectionName : String!
var sectionObjects : [String]!
var sectionImages : [String]!
}
var objectArray = [Objects]()
I have written following code for reading the file:
if let file = Bundle.main.url(forResource: "EventsEnglish112017", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data as Data, options: [])
My question is how do I typecast "json" to read the individual elements to fill the above objectArray.
Thanks!
A JSON is a dictionary of type [String:Any?]
To parse it:
if let dictionary = json as? [String: Any?] {
if let events = dictionary["events"] as? [[String: Any?]] {
// events is an array of JSON objects, so it's an array of dictionaries
for item in events
{
let date = item["date"] as? String // this is a String?
let name = item["name"] as? [String]
// same goes for 'photo'
}
}
}
Now that you have retrieved the data, you can use it to costruct your custom objects.
But it's better if you use some library that will make it for you, or use Swift4
To retrieve data from JSON file
(Swift 3)
if let path = NSBundle.mainBundle().pathForResource("myJson", ofType: "json")
{
if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
{
if let jsonResult = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? [String: Any]
{
if let eventsInfo = jsonResult["events"] as? [Any]
{
// Here you will get your data in Array format.
// for e.g
// print(eventsInfo[0]["date"])
// Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there.
}
}
}
}
(Swift 4)
if let path = Bundle.main.path(forResource: "myJson", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let eventsInfo = jsonResult["events"] as? [Any] {
// Here you will get your data in Array format.
// for e.g
// print(eventsInfo[0]["date"])
// Just pass this eventsInfo (Array) into you Object model initializer and parse with the keys there.
}
} catch {
// handle error
}
}

Get data from json array swift 2

I'm trying to get data drom the json array, this is the code that i'm trying, the thing is that i would like to get only the name that is inside this json
{
"tag": "getuser",
"success": 1,
"error": 0,
"uid": "56108b7e651ad2.95653404",
"user": {
"name": "2",
"phone": "2",
"email": "2"
}
}
I tryied this
let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
let name = jsonData["user"]
print("Nombre del usuarioes: \(name)")
But this prints the whole user data, name, phone and email, how can i be able to print only the name or only the email?
You don't have to use a library and you don't have to use key-value coding.
The same way you're already using subscripting for your dictionary with this:
let name = jsonData["user"]
you just have to continue subscripting to find your value.
Example:
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: []) as! NSDictionary
let user = jsonData["user"]!
let name = user["name"]
print(name)
} catch {
print(error)
}
Even better with safe unwrapping:
do {
if let data = urlData, let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
if let user = jsonData["user"] as? NSDictionary, let name = user["name"] as? String {
print(name)
}
}
} catch {
print(error)
}
Note: in JSON, a dictionary is defined by {} and an array is defined by []. What you have here is a dictionary containing a dictionary, not an array (cf your question title).
A great library to decode json is SwiftyJSON
you can get sub-scripted data from the json like so
import SwiftyJSON
if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
let name = json["user"]["name"].string
print(name)
}
Use your code, then get the field from jsonData by this:
let name = jsonData.valueForKeyPath("user.name") as! String
let email = jsonData.valueForKeyPath("user.email") as! String

Reading in a JSON File Using Swift

I'm really struggling with trying to read a JSON file into Swift so I can play around with it. I've spent the best part of 2 days re-searching and trying different methods but no luck as of yet so I have signed up to StackOverFlow to see if anyone can point me in the right direction.....
My JSON file is called test.json and contains the following:
{
"person":[
{
"name": "Bob",
"age": "16",
"employed": "No"
},
{
"name": "Vinny",
"age": "56",
"employed": "Yes"
}
]
}
The file is stored in the documents directly and I access it using the following code:
let file = "test.json"
let dirs : String[] = NSSearchPathForDirectoriesInDomains(
NSSearchpathDirectory.DocumentDirectory,
NSSearchPathDomainMask.AllDomainMask,
true) as String[]
if (dirs != nil) {
let directories: String[] = dirs
let dir = directories[0]
let path = dir.stringByAppendingPathComponent(file)
}
var jsonData = NSData(contentsOfFile:path, options: nil, error: nil)
println("jsonData \(jsonData)" // This prints what looks to be JSON encoded data.
var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as? NSDictionary
println("jsonDict \(jsonDict)") - This prints nil.....
If anyone can just give me a push in the right direction on how I can de-serialize the JSON file and put it in an accessible Swift object I will be eternally grateful!
Kind Regards,
Krivvenz.
Follow the below code :
if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json")
{
if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
{
if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
{
if let persons : NSArray = jsonResult["person"] as? NSArray
{
// Do stuff
}
}
}
}
The array "persons" will contain all data for key person. Iterate throughs to fetch it.
Swift 4.0:
if let path = Bundle.main.path(forResource: "test", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
// do stuff
}
} catch {
// handle error
}
}
Swift 4.x and 5.x using Decodable
struct ResponseData: Decodable {
var person: [Person]
}
struct Person : Decodable {
var name: String
var age: String
var employed: String
}
func loadJson(filename fileName: String) -> [Person]? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(ResponseData.self, from: data)
return jsonData.person
} catch {
print("error:\(error)")
}
}
return nil
}
Swift 3
func loadJson(filename fileName: String) -> [String: AnyObject]? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
return dictionary
}
} catch {
print("Error!! Unable to parse \(fileName).json")
}
}
return nil
}
If anyone is looking for SwiftyJSON Answer:
Update:
For Swift 3/4:
if let path = Bundle.main.path(forResource: "assets/test", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jsonObj = try JSON(data: data)
print("jsonData:\(jsonObj)")
} catch let error {
print("parse error: \(error.localizedDescription)")
}
} else {
print("Invalid filename/path.")
}
Swift 5.1, Xcode 11
You can use this:
struct Person : Codable {
let name: String
let lastName: String
let age: Int
}
func loadJson(fileName: String) -> Person? {
let decoder = JSONDecoder()
guard
let url = Bundle.main.url(forResource: fileName, withExtension: "json"),
let data = try? Data(contentsOf: url),
let person = try? decoder.decode(Person.self, from: data)
else {
return nil
}
return person
}
Xcode 8 Swift 3 read json from file update:
if let path = Bundle.main.path(forResource: "userDatabseFakeData", ofType: "json") {
do {
let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe)
do {
let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
if let people : [NSDictionary] = jsonResult["person"] as? [NSDictionary] {
for person: NSDictionary in people {
for (name,value) in person {
print("\(name) , \(value)")
}
}
}
} catch {}
} catch {}
}
Simplifying the example provided by Peter Kreinz. Works with Swift 4.2.
The extension function:
extension Decodable {
static func parse(jsonFile: String) -> Self? {
guard let url = Bundle.main.url(forResource: jsonFile, withExtension: "json"),
let data = try? Data(contentsOf: url),
let output = try? JSONDecoder().decode(self, from: data)
else {
return nil
}
return output
}
}
The example model:
struct Service: Decodable {
let name: String
}
The example usage:
/// service.json
/// { "name": "Home & Garden" }
guard let output = Service.parse(jsonFile: "service") else {
// do something if parsing failed
return
}
// use output if all good
The example will work with arrays, too:
/// services.json
/// [ { "name": "Home & Garden" } ]
guard let output = [Service].parse(jsonFile: "services") else {
// do something if parsing failed
return
}
// use output if all good
Notice how we don't provide any unnecessary generics, thus we don't need to cast the result of parse.
Updated names for Swift 3.0
Based on Abhishek's answer and Druva's answer
func loadJson(forFilename fileName: String) -> NSDictionary? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
if let data = NSData(contentsOf: url) {
do {
let dictionary = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments) as? NSDictionary
return dictionary
} catch {
print("Error!! Unable to parse \(fileName).json")
}
}
print("Error!! Unable to load \(fileName).json")
}
return nil
}
Swift 2.1 answer (based on Abhishek's) :
if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json") {
do {
let jsonData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
do {
let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if let people : [NSDictionary] = jsonResult["person"] as? [NSDictionary] {
for person: NSDictionary in people {
for (name,value) in person {
print("\(name) , \(value)")
}
}
}
} catch {}
} catch {}
}
Swift 3.0, Xcode 8, iOS 10
if let path = Bundle.main.url(forResource: "person", withExtension: "json") {
do {
let jsonData = try Data(contentsOf: path, options: .mappedIfSafe)
do {
if let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? NSDictionary {
if let personArray = jsonResult.value(forKey: "person") as? NSArray {
for (_, element) in personArray.enumerated() {
if let element = element as? NSDictionary {
let name = element.value(forKey: "name") as! String
let age = element.value(forKey: "age") as! String
let employed = element.value(forKey: "employed") as! String
print("Name: \(name), age: \(age), employed: \(employed)")
}
}
}
}
} catch let error as NSError {
print("Error: \(error)")
}
} catch let error as NSError {
print("Error: \(error)")
}
}
Output:
Name: Bob, age: 16, employed: No
Name: Vinny, age: 56, employed: Yes
This worked great with me
func readjson(fileName: String) -> NSData{
let path = NSBundle.mainBundle().pathForResource(fileName, ofType: "json")
let jsonData = NSData(contentsOfMappedFile: path!)
return jsonData!
}
Here is my solution using SwiftyJSON
if let path : String = NSBundle.mainBundle().pathForResource("filename", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
let json = JSON(data: data)
}
}
fileprivate class BundleTargetingClass {}
func loadJSON<T>(name: String) -> T? {
guard let filePath = Bundle(for: BundleTargetingClass.self).url(forResource: name, withExtension: "json") else {
return nil
}
guard let jsonData = try? Data(contentsOf: filePath, options: .mappedIfSafe) else {
return nil
}
guard let json = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) else {
return nil
}
return json as? T
}
👆🏻 copy-paste ready, 3rd party framework independent solution.
usage 👇🏻
let json:[[String : AnyObject]] = loadJSON(name: "Stations")!
Swift 4: Try out my solution:
test.json
{
"person":[
{
"name": "Bob",
"age": "16",
"employed": "No"
},
{
"name": "Vinny",
"age": "56",
"employed": "Yes"
}
]
}
RequestCodable.swift
import Foundation
struct RequestCodable:Codable {
let person:[PersonCodable]
}
PersonCodable.swift
import Foundation
struct PersonCodable:Codable {
let name:String
let age:String
let employed:String
}
Decodable+FromJSON.swift
import Foundation
extension Decodable {
static func fromJSON<T:Decodable>(_ fileName: String, fileExtension: String="json", bundle: Bundle = .main) throws -> T {
guard let url = bundle.url(forResource: fileName, withExtension: fileExtension) else {
throw NSError(domain: NSURLErrorDomain, code: NSURLErrorResourceUnavailable)
}
let data = try Data(contentsOf: url)
return try JSONDecoder().decode(T.self, from: data)
}
}
Example:
let result = RequestCodable.fromJSON("test") as RequestCodable?
result?.person.compactMap({ print($0) })
/*
PersonCodable(name: "Bob", age: "16", employed: "No")
PersonCodable(name: "Vinny", age: "56", employed: "Yes")
*/
Use this generic function
func readJSONFromFile<T: Decodable>(fileName: String, type: T.Type) -> T? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(T.self, from: data)
return jsonData
} catch {
print("error:\(error)")
}
}
return nil
}
with this line of code:
let model = readJSONFromFile(fileName: "Model", type: Model.self)
for this type:
struct Model: Codable {
let tall: Int
}
I'm providing another answer because none of the ones here are geared toward loading the resource from the test bundle. If you are consuming a remote service that puts out JSON and want to unit test parsing the results without hitting the actual service, you take one or more responses and put them into files in the Tests folder in your project.
func testCanReadTestJSONFile() {
let path = NSBundle(forClass: ForecastIOAdapterTests.self).pathForResource("ForecastIOSample", ofType: "json")
if let jsonData = NSData(contentsOfFile:path!) {
let json = JSON(data: jsonData)
if let currentTemperature = json["currently"]["temperature"].double {
println("json: \(json)")
XCTAssertGreaterThan(currentTemperature, 0)
}
}
}
This also uses SwiftyJSON but the core logic of getting the test bundle and loading the file is the answer to the question.
The following code works for me. I am using Swift 5
let path = Bundle.main.path(forResource: "yourJSONfileName", ofType: "json")
var jsonData = try! String(contentsOfFile: path!).data(using: .utf8)!
Then, if your Person Struct (or Class) is Decodable (and also all of its properties), you can simply do:
let person = try! JSONDecoder().decode(Person.self, from: jsonData)
I avoided all the error handling code to make the code more legible.
Updated for Swift 3 with safest way
private func readLocalJsonFile() {
if let urlPath = Bundle.main.url(forResource: "test", withExtension: "json") {
do {
let jsonData = try Data(contentsOf: urlPath, options: .mappedIfSafe)
if let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String: AnyObject] {
if let personArray = jsonDict["person"] as? [[String: AnyObject]] {
for personDict in personArray {
for (key, value) in personDict {
print(key, value)
}
print("\n")
}
}
}
}
catch let jsonError {
print(jsonError)
}
}
}
Latest swift 3.0 absolutely working
func loadJson(filename fileName: String) -> [String: AnyObject]?
{
if let url = Bundle.main.url(forResource: fileName, withExtension: "json")
{
if let data = NSData(contentsOf: url) {
do {
let object = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
return dictionary
}
} catch {
print("Error!! Unable to parse \(fileName).json")
}
}
print("Error!! Unable to load \(fileName).json")
}
return nil
}
Swift 4 JSON to Class with Decodable - for those who prefer classes
Define the classes as follows:
class People: Decodable {
var person: [Person]?
init(fileName : String){
// url, data and jsonData should not be nil
guard let url = Bundle.main.url(forResource: fileName, withExtension: "json") else { return }
guard let data = try? Data(contentsOf: url) else { return }
guard let jsonData = try? JSONDecoder().decode(People.self, from: data) else { return }
// assigns the value to [person]
person = jsonData.person
}
}
class Person : Decodable {
var name: String
var age: String
var employed: String
}
Usage, pretty abstract:
let people = People(fileName: "people")
let personArray = people.person
This allow methods for both People and Person classes, variables (attributes) and methods can also marked as private if needed.
Swift 5+
Decoding the jsonData with your Struct
if let jsonData = readFile(forName: <your file name>) {
do {
let decodedData = try JSONDecoder().decode(<your struct name>.self, from: jsonData)
return decodedData.<what you expect>
} catch { print("JSON decode error") }
}
This will read the file and return jsonData
In case you are actually in another bundle (test for instance), use:
let bundlePath = Bundle(for: type(of: self)).path(forResource: name, ofType: "json")
private func readFile(forName name: String) -> Data? {
do {
if let bundlePath = Bundle.main.path(forResource: name, ofType: "json"),
let jsonData = try String(contentsOfFile: bundlePath).data(using: .utf8) {
return jsonData
}
} catch {
print(error)
}
return nil
}
I wasted my time in locating file which was located in my project with name Jsondata.json. But I weren't able to locate my File through code....
Solution: Make sure that your Jsondata.json file is added in Project> Build Phases> Copy Bundle Resources. Otherwise you wont be able to get file and Bundle.main.url(forResource: fileName, withExtension: "json") will give you nil always.
One more answer here???
Ok. Hold on! All of the answers before were about using JSONSerialization, or returns nil, or ignores errors.
What is the different
"My solution" (is is not really my, this is a mix of the solutions above) contains:
Modern way to return values: Result<Value,Error> (returns Value or Error)
Avoids nil usage
Contains a slightly verbose error
Uses extension to have pretty/intuitive interface: Model.from(localJSON: "myJsonFile")
Gives possibility to select bundle
Details
Xcode 14
Swift 5.6.1
Solution 1. JSON file -> Decodable
enum JSONParseError: Error {
case fileNotFound
case dataInitialisation(error: Error)
case decoding(error: Error)
}
extension Decodable {
static func from(localJSON filename: String,
bundle: Bundle = .main) -> Result<Self, JSONParseError> {
guard let url = bundle.url(forResource: filename, withExtension: "json") else {
return .failure(.fileNotFound)
}
let data: Data
do {
data = try Data(contentsOf: url)
} catch let error {
return .failure(.dataInitialisation(error: error))
}
do {
return .success(try JSONDecoder().decode(self, from: data))
} catch let error {
return .failure(.decoding(error: error))
}
}
}
Solution 1 Usage
struct Model: Decodable {
let uuid: String
let name: String
}
switch Model.from(localJSON: "myjsonfile") {
case .success(let value):
print(value)
case .failure(let error):
print(error)
}
Solution 2. JSON file -> Dictionary
extension Dictionary where Key == String, Value == Any {
enum JSONParseError: Error {
case fileNotFound(filename: String)
case dataInitialisation(Error)
case jsonSerialization(Error)
case mappingFail(value: Any, toType: Any)
}
static func from(JSONfile url: URL) -> Result<Self, JSONParseError> {
let data: Data
do {
data = try Data(contentsOf: url)
} catch let error {
return .failure(.dataInitialisation(error))
}
let jsonObject: Any
do {
jsonObject = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
} catch let error {
return .failure(.jsonSerialization(error))
}
guard let jsonResult = jsonObject as? Self else {
return .failure(.mappingFail(value: jsonObject, toType: Self.Type.self))
}
return .success(jsonResult)
}
static func from(localJSONfile name: String) -> Result<Self, JSONParseError> {
let fileType = "json"
let fullFileName = name + (name.contains(fileType) ? "" : ".\(fileType)")
guard let path = Bundle.main.path(forResource: fullFileName, ofType: "") else {
return .failure(.fileNotFound(filename: fullFileName))
}
return from(JSONfile: URL(fileURLWithPath: path))
}
}
Solution 2 Usage
switch [String: Any].from(localJSONfile: "file.json") {
// OR switch [String: Any].from(localJSONfile: "file.json") {
// OR switch [String: Any].from(JSONfile: url) {
case let .success(dictionary):
print(dictionary)
case let .failure(error):
print("ERROR: \(error)")
}
Based on Abhishek's answer, for iOS 8 this would be:
let masterDataUrl: NSURL = NSBundle.mainBundle().URLForResource("masterdata", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: masterDataUrl)!
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as! NSDictionary
var persons : NSArray = jsonResult["person"] as! NSArray
This worked for me with XCode 8.3.3
func fetchPersons(){
if let pathURL = Bundle.main.url(forResource: "Person", withExtension: "json"){
do {
let jsonData = try Data(contentsOf: pathURL, options: .mappedIfSafe)
let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as! [String: Any]
if let persons = jsonResult["person"] as? [Any]{
print(persons)
}
}catch(let error){
print (error.localizedDescription)
}
}
}
Swift 4.1 Updated Xcode 9.2
if let filePath = Bundle.main.path(forResource: "fileName", ofType: "json"), let data = NSData(contentsOfFile: filePath) {
do {
let json = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.allowFragments)
}
catch {
//Handle error
}
}
//change type based on your struct and right JSON file
let quoteData: [DataType] =
load("file.json")
func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
}
}
Swift 5 answer worked for me, except that is missing that i must add a empty file, rename it as xxx.json after it works, and using generics.
func loadJson<T:Codable>(filename fileName: String) -> T? {
if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
print("error:\(error)")
}
}
return nil
}
code
I’ve used below code to fetch JSON from FAQ-data.json file present in project directory .
I’m implementing in Xcode 7.3 using Swift.
func fetchJSONContent() {
if let path = NSBundle.mainBundle().pathForResource("FAQ-data", ofType: "json") {
if let jsonData = NSData(contentsOfFile: path) {
do {
if let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
if let responseParameter : NSDictionary = jsonResult["responseParameter"] as? NSDictionary {
if let response : NSArray = responseParameter["FAQ"] as? NSArray {
responseFAQ = response
print("response FAQ : \(response)")
}
}
}
}
catch { print("Error while parsing: \(error)") }
}
}
}
override func viewWillAppear(animated: Bool) {
fetchFAQContent()
}
Structure of JSON file :
{
"status": "00",
"msg": "FAQ List ",
"responseParameter": {
"FAQ": [
{
"question": “Question No.1 here”,
"answer": “Answer goes here”,
"id": 1
},
{
"question": “Question No.2 here”,
"answer": “Answer goes here”,
"id": 2
}
. . .
]
}
}
I might also recommend Ray Wenderlich's Swift JSON Tutorial (which also covers the awesome SwiftyJSON alternative, Gloss). An excerpt (which granted, by itself, does not fully answer the poster, but the added value of this answer is the link, so no -1's for that, please):
In Objective-C, parsing and deserializing JSON is fairly straightforward:
NSArray *json = [NSJSONSerialization JSONObjectWithData:JSONData
options:kNilOptions error:nil];
NSString *age = json[0][#"person"][#"age"];
NSLog(#"Dani's age is %#", age);
In Swift, parsing and deserializing JSON is a little more tedious due to Swift optionals and type-safety [but as] part of Swift 2.0 the guard statement was introduced to help get rid of nested if statements:
var json: Array!
do {
json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions()) as? Array
} catch {
print(error)
}
guard let item = json[0] as? [String: AnyObject],
let person = item["person"] as? [String: AnyObject],
let age = person["age"] as? Int else {
return;
}
print("Dani's age is \(age)")
Of course, in XCode 8.x, you just double-tap the space bar and say "Hey, Siri, please deserialize this JSON for me in Swift 3.0 with space/tab-indents."
SWIFTYJSON VERSION SWIFT 3
func loadJson(fileName: String) -> JSON {
var dataPath:JSON!
if let path : String = Bundle.main.path(forResource: fileName, ofType: "json") {
if let data = NSData(contentsOfFile: path) {
dataPath = JSON(data: data as Data)
}
}
return dataPath
}