jsonswift4swifty-jsonalgorithmia

How to append data to a JSON value of type array in swift 4


This is my code of the json object. I'm trying to get an image dictionary into the images value. I've tried a lot of things and maybe I'm missing something.

 let jsonObject: [String: Any] = [
        "name_space": "users",
        "data_collection": "data://brownfosman5000/DatFace/",
        "action" : "add_images",
        "images": []
    ]

I have created a json dictionary to hold the images

let imageDictionary = try! JSONSerialization.jsonObject(with: imageJSON, options: []) as! [String : Any]

I have also created an array to hold the array of imageDictionaries

let images:NSMutableArray = NSMutableArray()
self.images.add(imageDictionary)

How can I add the images array to the array in my json as a dictionary? Everything prints out nice I just need to add it to the json.


Solution

  • First of all never use NSMutable... collection types in Swift. Use a native type with the var keyword

    var images = [[String:Any]]()
    

    Second of all make jsonObject also mutable

    var jsonObject: [String: Any] = [ ...
    

    Append the dictionary to images

    images.append(imageDictionary)
    

    Assign the array to the dictionary for key images

    jsonObject["images"] = images