Creative crypter
Creative crypter

Reputation: 1496

SwiftyJSON Append new data to existing JSON array

I am working on a way to add new JSON data to my existing JSON array:

var resources: JSON = [
    "resources": []
]

override func viewDidLoad() {
    super.viewDidLoad()

    getApiResourceA() { responseObject, error in
        var resourceA: JSON = [
            "resourceA": []
        ]

        let resourceAResponseObject = JSON(responseObject!)
        resourceA["resourceA"] = resourceAResponseObject
        self.resources["resources"] = resourceA
    }

    getApiResourceB() { responseObject, error in
        var resourceB: JSON = [
            "resourceB": []
        ]

        let resourceBResponseObject = JSON(responseObject!)
        resourceB["resourceB"] = resourceBResponseObject
        self.resources["resources"] = resourceB
    }
}

The structure I am trying to get is:

{
    "resources": {
        "resourceA": {
            "id": 1
            "name": "Name1"
        }
        "resourceB": {
            "id": 2
            "name": "Name2"
        }
    }
}

But in my code there are two different "resources"-array created...

Anyone know how to deal with this?

Upvotes: 2

Views: 2981

Answers (2)

Gerson Montenegro
Gerson Montenegro

Reputation: 486

@daniel-krom has right, but is a little confusing implement the extension, so, we need only add at the end of the Swift controller (or class) that code that adds the "append" methods, nothing else.

Using the appendIfArray method, I could pass from this

[
  {
    "id_usuario" : 2
  }
]

...to this

[
  {
    "id_usuario" : 2
  },
  {
    "id_usuario" : 111
  },
  {
    "id_usuario" : 112
  },
  {
    "id_usuario" : 113
  }
]

The complete code is below:

do{
    try json2!["usuarios"][indice]["fotos"][0]["me_gusta"].appendIfArray(json: JSON( ["id_usuario": 111] ))
    try json2!["usuarios"][indice]["fotos"][0]["me_gusta"].appendIfArray(json: JSON( ["id_usuario": 112] ))
    try json2!["usuarios"][indice]["fotos"][0]["me_gusta"].appendIfArray(json: JSON( ["id_usuario": 113] ))
}catch {
    print("Error")
}

The complete JSON structure can find in

http://jsoneditoronline.org/?id=56988c404dcd3c8b3065a583f9a41bba

I hope this can be useful

Upvotes: 0

Daniel Krom
Daniel Krom

Reputation: 10060

First it is important to understand that JSON is Struct means it is duplicated every time you pass it or use it.

Another issue, you declared resources as Array and not as Dictionary means you can use resource as key.

Declare extensions:

extension JSON{
    mutating func appendIfArray(json:JSON){
        if var arr = self.array{
            arr.append(json)
            self = JSON(arr);
        }
    }

    mutating func appendIfDictionary(key:String,json:JSON){
        if var dict = self.dictionary{
            dict[key] = json;
            self = JSON(dict);
        }
    }
}

use:

//notice the change [String:AnyObject]
var resources: JSON = [
    "resources": [String:AnyObject](),
]

resources["resources"].appendIfDictionary("resourceA", json: JSON(["key1":"value1"]))
resources["resources"].appendIfDictionary("resourceB", json: JSON(["key2":"value2"]))

result:

{
  "resources" : {
    "resourceB" : {
      "key2" : "value2"
    },
    "resourceA" : {
      "key1" : "value1"
    }
  }
}

Upvotes: 2

Related Questions