17

I have an array of SwiftyJson data that I have declared and filled it with data .The code I'm using to fill the hoge array is this : self.hoge = JSON(data: data!)

but I need to append new swiftyJSON data to this hoge array .I noticed hoge array doesn't have append property . How should I do that?

Thanks

user970956
  • 319
  • 1
  • 5
  • 13
  • @adnan I have declared hoge like this ` var hoge:JSON = []` and as soon as I changed it's type to NSMutableArray I got error that says JSON is not convertible to NSMutableArray . What I have done wrong?Thanks – user970956 Mar 14 '15 at 07:39
  • I agree, I think swiftyjson could have more user friendly documentation :> – user798719 Sep 30 '18 at 14:52

7 Answers7

19

SwiftyJSON does not have append or extend functionality.

You can:

self.hoge = JSON(self.hoge.arrayObject! + JSON(data: newData).arrayObject!)

But I recommend to declare self.hoge as [JSON]

var hoge:[JSON] = []

func readMoreData() {

    let newData: NSData = ...

    if let newArray = JSON(data:newData).array {
        self.hoge += newArray
    }
}
rintaro
  • 51,423
  • 14
  • 131
  • 139
  • .Thanks it works fine and add new data to hoge. the only problem left is that I used to return datas from hoge like this `self.hoge[indexPath.row]["cars"]["pic_name"]` but now I got error that says cannot index empty buffer . How should I return data now? Thanks again – user970956 Mar 14 '15 at 08:09
  • 3
    Tried it, but += operator does not seem to work with JSON objects. Please correct me if I am wrong. – Yuichi Kato Aug 15 '15 at 17:21
9

Swift 2-4

Another solution, using Extension

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:

var myJSON: JSON = [
    "myDictionary": [String:AnyObject](),
    "myArray" : [1,2,3,4]
]

myJSON["myDictionary"].appendIfDictionary(key:"A", json: JSON(["key1":"value1"]))
myJSON["myDictionary"].appendIfDictionary(key: "B", json: JSON(["key2":"value2"]))
myJSON["myArray"].appendIfArray(json: JSON(5))

print:

{
  "myArray" : [
    1,
    2,
    3,
    4,
    5
  ],
  "myDictionary" : {
    "B" : {
      "key2" : "value2"
    },
    "A" : {
      "key1" : "value1"
    }
  }
}
Community
  • 1
  • 1
Daniel Krom
  • 9,751
  • 3
  • 43
  • 44
  • but it's not saving...." was compiled with optimization - stepping may behave oddly; variables may not be available." error appeared and after closing the app, nothing changes – Dumitru Rogojinaru Feb 02 '17 at 11:42
  • @DumitruRogojinaru I didn't test that on swift 3 so I guess something was changed, I'll update my answer in the next few days – Daniel Krom Feb 02 '17 at 11:51
6

You can use the merge function for this. https://github.com/SwiftyJSON/SwiftyJSON#merging

var array: JSON = [1, 2, 3]
array = try! array.merged(with: [4])
// -> [1, 2, 3, 4]
Lindemann
  • 3,336
  • 3
  • 29
  • 27
5
let jsonNewJSON:JSON = JSON(newData)
var arr:[JSON]=jsonOBJ.arrayValue
arr.append(jsonNewJSON)
var combinedOBJ = JSON(arr)

I used the above code to append to a swiftyjson array . I first converted the new data to a JSON object. Then I got the array of the existing JSON and append the new JSON. I converted the array back to a JSON object. Admit-ably not great code, but I did not need performance here and it got the job done.

yeahdixon
  • 6,647
  • 1
  • 41
  • 43
1

Declare you main JSON Array as :

var data:[JSON] = []

If the data source is any other object (like realm) loop over it using for loop But if the data source is another JSON Array perform :

func setData(){
        data = []
        if let items = sourceData.array {
            for item in items {
              data.append(item)
            }
        }
        collectionView.reloadData()
    }
Moonis Abidi
  • 663
  • 10
  • 15
0

self.hoge should be a Swift Array (which is mutable if declared as var) or casted to a NSMutableArray. If it is of Array type use append. If casted to an NSMutableArray use self.hoge.addObject(yourObject).

Nikos M.
  • 13,685
  • 4
  • 47
  • 61
  • I have declared hoge like this var hoge:JSON = [] .How should I modified that?I tied to convert it to NSMutableArray which gave me an error that JSON is not convertible to NSMutableArray . Could you help me with that Please?Thanks – user970956 Mar 14 '15 at 07:35
  • declare it as `hoge = [JSON]()` – Nikos M. Mar 14 '15 at 07:41
0

I needed to add a dictionary to the JSON data in my project. I added to Daniel Krom's answer above:

import SwiftyJSON

extension JSON {
    
    mutating func appendIfKeyValuePair(key: String, value: Any){
        if var dict = self.dictionaryObject {
            dict[key] = value
            self = JSON(dict)
        }
    }
}

Usage:

var data: JSON = []

data.appendIfKeyValuePair(key: "myKey", value: "myValue")
GIJoeCodes
  • 1,680
  • 1
  • 25
  • 28