[英]Appending JSON array with values from the array
I have a json array with the following structure 我有一个具有以下结构的json数组
{
"connection": {
"established": "yes"
},
"ping": {
"server": "thirteen"
}
}
also i have a simple array of server names called servers
我也有一个简单的服务器名称数组,称为servers
my goal is to append the values from the servers
array to the Json
array - copying the "connection", "established", "yes", "ping", "server" values and just modifying the "thirteen" value. 我的目标是将servers
数组中的值附加到Json
数组-复制“连接”,“已建立”,“是”,“ ping”,“服务器”值,并仅修改“十三”值。
So that the end result would look something like this 这样最终结果看起来像这样
{
"connection": {
"established": "yes"
},
"ping": {
"server": "fourteen"
}
},
{
"connection": {
"established": "yes"
},
"ping": {
"server": "fifteen"
}
}
etc 等等
I tried implementing the SwiftyJSON
array library, but didn't really understand how to append values to the json itself. 我尝试实现SwiftyJSON
数组库,但并没有真正理解如何将值附加到JSON本身。
Is there a way to manage it? 有办法管理吗?
Appreciate any insights! 感谢任何见解!
I hope this is what you are looking for. 我希望这是您要寻找的。 It took me some time to understand what you are asking for :) 我花了一些时间来了解您的要求:)
// 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)")
使用SwiftyJSON尝试一下(未测试)
Json["ping"] as NSDictionary)["server"] as NSString = "Your Value"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.