Modify an array of json objects

217 Views Asked by At

I have a list of json objects which I need to modify the values within each of them. I'm accessing this list of json objects in the below piece of code:

            if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            
            let objects = json["data"] as? [String: Any]
            if let accounts = objects?["accounts"] as? [[String:Any]]{
                
                print("Accounts: \(accounts)")
                for account in accounts {
                    account["balance"] = nil
                }
            }
            
            modifiedData = try JSONSerialization.data(withJSONObject: json, options: [])
        }

But the accounts array is immutable. I've tried casting to NSMutableDictionary and NSMutableArray but can't seem to get it to work. Does anyone have any tips?

1

There are 1 best solutions below

2
Joakim Danielson On BEST ANSWER

You need to work with var declared variables instead and access the accounts array by index instead

if var json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
    var objects = json["data"] as? [String: Any]
    if var accounts = objects?["accounts"] as? [[String:Any]] {
        for index in 0..<accounts.count {
            accounts[index]["balance"] = 0
        }
        objects?["accounts"] = accounts
    }
    json["data"] = objects
}