我有一个具有以下结构的json数组
{
"connection": {
"established": "yes"
},
"ping": {
"server": "thirteen"
}
}
我也有一个简单的服务器名称数组,名为servers
我的目标是将servers
数组中的值附加到Json
数组 - 复制“connection”,“established”,“yes”,“ping”,“server” “值,只修改”十三“值。
所以最终结果看起来像这样
{
"connection": {
"established": "yes"
},
"ping": {
"server": "fourteen"
}
},
{
"connection": {
"established": "yes"
},
"ping": {
"server": "fifteen"
}
}
e.t.c。
我尝试实现SwiftyJSON
数组库,但并不真正了解如何将值附加到json本身。
有办法管理吗?
欣赏任何见解!
答案 0 :(得分:1)
我希望这就是你要找的东西。我花了一些时间来了解你的要求:)
// 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($0)
})[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)")
答案 1 :(得分:0)
使用SwiftyJSON(未测试)
尝试此操作Json["ping"] as NSDictionary)["server"] as NSString = "Your Value"