更改可嵌套在Swift中的键的JSON值

时间:2019-03-06 09:36:45

标签: ios json swift

我不知道是否有更快捷的方法或针对我的问题已经实现的功能。我有一个带有 unique 键的嵌套动态JSON。

{
    "Key1": true,
    "Key2": false,
    "Key3": "just a string",
    "Key4": {
               "Key5": "just a string",
               "Key6": 51,
               "Key7": {
                           "Key8": "this value has to be changed"
                       }
            }
}

是否有任何Swift函数或软件包可以像这样轻松地做到这一点:

let updatedJSON = originalJSON.update(key: "Key8", with: "---")

因此,updatedJSON将相同,仅“ Key8”将被更新。考虑到我不知道层次结构。 JSON键位置可能会引起注意。有时Key8可以位于对象的根。

1 个答案:

答案 0 :(得分:1)

不知道JSON的结构会使这个问题稍微复杂一些,但是仍然可以解决。我想出了一个通过字典递归搜索的想法

extension Dictionary
{
    mutating func updateValueRecursively(forKey key : Key, newValue: Value) -> Bool
    {
        if keys.contains(key)
        {
            self[key] = newValue
            return true
        }
        for (_, value) in enumerated()
        {
            if var dict = value.value as? Dictionary<Key, Value> {
                if dict.updateValueRecursively(forKey: value.key, newValue: newValue), let newDict = dict as? Value {
                    self[value.key] = newDict
                    return true
                }
            }
        }
        return false
    }
}

当然,您首先必须将JSON字符串转换为Dictionary

var dict : Dictionary<String : Any>
if let data = jsonString.data(using: .utf8) {
do {
    dict=  try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
    print(error.localizedDescription)
}