使用数组中的值追加 JSON 数组

Appending JSON array with values from the array

我有一个具有以下结构的 json 数组

{
        "connection": {
            "established": "yes"
        },
        "ping": {
            "server": "thirteen"
        }
    }

我还有一个简单的服务器名称数组,名为 servers

我的目标是将 servers 数组中的值附加到 Json 数组 - 复制 "connection"、"established"、"yes"、"ping"、"server" 值,只需修改 "thirteen" 值。

这样最终的结果就会像这样

{
        "connection": {
            "established": "yes"
        },
        "ping": {
            "server": "fourteen"
        }
    }, 
{
        "connection": {
            "established": "yes"
        },
        "ping": {
            "server": "fifteen"
        }
    }

e.t.c.

我尝试实现 SwiftyJSON 数组库,但并不真正理解如何将值附加到 json 本身。

有办法管理吗?

感谢任何见解!

尝试使用 SwiftyJSON(未测试)

Json["ping"] as NSDictionary)["server"] as NSString = "Your Value"

希望这就是您要找的。我花了一些时间才明白你的要求:)

// Initial Data - So called JSON Array
var dict1 = ["connection" : ["established": "yes"], "ping" : ["server" : "twelve"]]
var dict2 = ["connection" : ["established": "yes"], "ping" : ["server" : "thirteen"]]
var array = [dict1, dict2]

// Servers Array
var servers = ["fourteen", "fifteen"]

// First lets filter out dictionary where ping.server = thirteen
let predicate = NSPredicate(format: "ping.server = %@", "thirteen")

// Filtered dictionary
var targetDict = array.filter({
    predicate.evaluateWithObject([=10=])
})[0]

// Now lets loop on servers and modify filtered dictionary and add to parent array
for server in servers {
    targetDict["ping"]!["server"]! = server
    array.append(targetDict)
}

print("\(array)")