简体   繁体   中英

Appending JSON array with values from the array

I have a json array with the following structure

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

also i have a simple array of server names called 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.

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM