Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an array as a json file in Swift?

Tags:

json

xcode

swift

I'm new at swift and I'm having trouble with this. so what i need to do is save this array as a json file in the document folder of the iphone.

var levels = ["unlocked", "locked", "locked"] 

and then later on be able to read it back into another array. Could someone please tell me how to do this? or provided with the exact code to accomplish this.

EDITED: I found one example of this. This is how they set up the data:

 "[ {"person": {"name":"Dani","age":"24"}}, {"person": {"name":"ray","age":"70"}} ]"  

and the you can access it this way:

 if let item = json[0]     { if let person = item["person"]       { if let age = person["age"]        { println(age) } } } 

But I need to be able to do the same but from a file that is saved on the document folder.

like image 849
elpita Avatar asked Feb 27 '15 14:02

elpita


People also ask

How do I save an array to a JSON file?

You convert the whole array to JSON as one object by calling JSON. stringify() on the array, which results in a single JSON string. To convert back to an array from JSON, you'd call JSON. parse() on the string, leaving you with the original array.

Can array be converted to JSON?

JS Array to JSON using JSON.stringify() method converts a JavaScript object, array, or value to a JSON string. If you so choose, you can then send that JSON string to a backend server using the Fetch API or another communication library.

How do I save a JSON response in Swift?

Save JSON string to file Saving a JSON string will be the same as saving any other kind of string. Since Swift will see it as a String object, we can use the write(to:) method that is built into String .

How do I save a JSON file?

In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON. Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as . JSON file, you have to just select the location of the file.


2 Answers

If you're like me who doesn't like to use a whole new third-party framework just for a trivial thing like this, here's my solution in vanilla Swift. From creating a .json file in the Documents folder to writing JSON in to it.

let documentsDirectoryPathString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! let documentsDirectoryPath = NSURL(string: documentsDirectoryPathString)!  let jsonFilePath = documentsDirectoryPath.URLByAppendingPathComponent("test.json") let fileManager = NSFileManager.defaultManager() var isDirectory: ObjCBool = false  // creating a .json file in the Documents folder if !fileManager.fileExistsAtPath(jsonFilePath.absoluteString, isDirectory: &isDirectory) {     let created = fileManager.createFileAtPath(jsonFilePath.absoluteString, contents: nil, attributes: nil)     if created {         print("File created ")     } else {         print("Couldn't create file for some reason")     } } else {     print("File already exists") }  // creating an array of test data var numbers = [String]() for var i = 0; i < 100; i++ {     numbers.append("Test\(i)") }  // creating JSON out of the above array var jsonData: NSData! do {     jsonData = try NSJSONSerialization.dataWithJSONObject(numbers, options: NSJSONWritingOptions())     let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding)     print(jsonString) } catch let error as NSError {     print("Array to JSON conversion failed: \(error.localizedDescription)") }  // Write that JSON to the file created earlier let jsonFilePath = documentsDirectoryPath.URLByAppendingPathComponent("test.json") do {     let file = try NSFileHandle(forWritingToURL: jsonFilePath)     file.writeData(jsonData)     print("JSON data was written to teh file successfully!") } catch let error as NSError {     print("Couldn't write to file: \(error.localizedDescription)") } 
like image 75
Isuru Avatar answered Sep 19 '22 08:09

Isuru


#1. Save a Swift Array as a json file

The following Swift 3 / iOS 10 code shows how to transform an Array instance into json data and save it into a json file located in an iPhone's document directory using FileManager and JSONSerialization:

func saveToJsonFile() {     // Get the url of Persons.json in document directory     guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }     let fileUrl = documentDirectoryUrl.appendingPathComponent("Persons.json")      let personArray =  [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]      // Transform array into data and save it into file     do {         let data = try JSONSerialization.data(withJSONObject: personArray, options: [])         try data.write(to: fileUrl, options: [])     } catch {         print(error)     } }  /*  Content of Persons.json file after operation:  [{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}] */ 

As an alternative, you can implement the following code that use streams:

func saveToJsonFile() {     // Get the url of Persons.json in document directory     guard let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }     let fileUrl = documentDirectoryUrl.appendingPathComponent("Persons.json")      let personArray =  [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]      // Create a write-only stream     guard let stream = OutputStream(toFileAtPath: fileUrl.path, append: false) else { return }     stream.open()     defer {         stream.close()     }      // Transform array into data and save it into file     var error: NSError?     JSONSerialization.writeJSONObject(personArray, to: stream, options: [], error: &error)      // Handle error     if let error = error {         print(error)     } }  /*  Content of Persons.json file after operation:  [{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}] */ 

#2. Get a Swift Array from a json file

The following Swift 3 / iOS 10 code shows how to get data from a json file located in an iPhone's document directory and transform it into an Array instance using FileManager and JSONSerialization:

/*  Content of Persons.json file:  [{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}] */  func retrieveFromJsonFile() {     // Get the url of Persons.json in document directory     guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }     let fileUrl = documentsDirectoryUrl.appendingPathComponent("Persons.json")      // Read data from .json file and transform data into an array     do {         let data = try Data(contentsOf: fileUrl, options: [])         guard let personArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: [String: String]]] else { return }         print(personArray) // prints [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]     } catch {         print(error)     } } 

As an alternative, you can implement the following code that use streams:

/*  Content of Persons.json file:  [{"person":{"name":"Dani","age":"24"}},{"person":{"name":"ray","age":"70"}}] */  func retrieveFromJsonFile() {     // Get the url of Persons.json in document directory     guard let documentsDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }     let fileUrl = documentsDirectoryUrl.appendingPathComponent("Persons.json")      // Create a read-only stream     guard let stream = InputStream(url: fileUrl) else { return }     stream.open()     defer {         stream.close()     }      // Read data from .json file and transform data into an array     do {         guard let personArray = try JSONSerialization.jsonObject(with: stream, options: []) as? [[String: [String: String]]] else { return }         print(personArray) // prints [["person": ["name": "Dani", "age": "24"]], ["person": ["name": "ray", "age": "70"]]]     } catch {         print(error)     } } 

The Playground located in the Github's Save-and-read-JSON-from-Playground repo shows how to save a Swift Array into a json file and how to read a json file and get a Swift Array from it.

like image 37
Imanou Petit Avatar answered Sep 22 '22 08:09

Imanou Petit