write to a json file in swift

To write to a JSON file in Swift, first you need to create a struct or class that conforms to the Codable protocol. This struct or class represents the structure of your JSON data. Then, you need to encode the data into a JSON format using the JSONEncoder. Finally, you need to write the data to the file system using the FileManager.

Here's an example:

main.swift
struct Person: Codable {
    var name: String
    var age: Int
}

let person = Person(name: "John Doe", age: 30)

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

if let data = try? encoder.encode(person),
   let jsonString = String(data: data, encoding: .utf8) {
    print(jsonString)
    
    let fileManager = FileManager.default
    let url = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("person.json")
    
    do {
        try jsonString.write(to: url, atomically: true, encoding: .utf8)
    } catch {
        print(error.localizedDescription)
    }
}
628 chars
24 lines

In this example, I created a Person struct that conforms to the Codable protocol. I then created an instance of Person and encoded it to a JSON format using the JSONEncoder. I also set the outputFormatting property to .prettyPrinted so that the JSON data is formatted nicely for readability.

Next, I created a FileManager instance to get the path to the user's documents directory. I then appended the file name "person.json" to the path and created a URL for the file. Finally, I wrote the encoded JSON data to the file using the write method of the String class. I also added error handling to catch any exceptions that may be thrown during the file writing process.

Note that this is a simple example and error handling can be improved depending on your use case.

gistlibby LogSnag