append to a json file in swift

To append data to a JSON file in Swift, you can follow these steps:

  1. Create a Swift dictionary with the data you want to append to the JSON file.

    main.swift
    let newData = ["key": "value"]
    
    31 chars
    2 lines
  2. Open the JSON file for writing.

    main.swift
    guard let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("example.json") else {
        fatalError("Failed to get file URL")
    }
    
    var jsonData = try Data(contentsOf: fileURL)
    
    233 chars
    6 lines
  3. Decode the JSON data from the file into a Swift dictionary.

    main.swift
    var existingData: [String: Any] = [:]
    if !jsonData.isEmpty {
        existingData = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] ?? [:]
    }
    
    169 chars
    5 lines
  4. Merge the new data with the existing data to create a new dictionary.

    main.swift
    let mergedData = existingData.merging(newData, uniquingKeysWith: { (_, last) in last })
    
    88 chars
    2 lines
  5. Encode the merged data as JSON.

    main.swift
    jsonData = try JSONSerialization.data(withJSONObject: mergedData, options: [.prettyPrinted])
    
    93 chars
    2 lines
  6. Write the JSON data back to the file, appending to the end of the file.

    main.swift
    if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
         defer {
             fileHandle.closeFile()
         }
         fileHandle.seekToEndOfFile()
         fileHandle.write(jsonData)
     } else {
         try jsonData.write(to: fileURL, options: .atomic)
     }
    
    251 chars
    10 lines

The atomic option ensures that the file is written atomically, meaning that the data is first written to a temporary file and then moved to the original file. This ensures that the file is not corrupted if the write operation is interrupted.

Note: It's important to ensure that the file you're writing to is a valid JSON file, otherwise the JSON decoding/encoding operations will fail.

gistlibby LogSnag