How to combine two SwiftyJSON objects
Asked Answered
C

5

6

I have a swiftyJSON object that looks like for example:

[{
  "location" : "http://...",
  "img" : "http://...",
  "commentCount" : 0,
  "timestamp" : 1432460217550,
}]

I want to be able to append another swiftyJSON object to it so that it looks like:

[{
  "location" : "http://...",
  "img" : "http://...",
  "commentCount" : 0,
  "timestamp" : 1432460217550,
},
{
  "location" : "http://...",
  "img" : "http://...",
  "commentCount" : 1,
  "timestamp" : 1432460217571,
}
]

I can't use += or .append on swiftyJSON objects. How can I do this?

Chargeable answered 24/5, 2015 at 19:33 Comment(0)
C
1

Victor's answer didn't work for me. But I solved the question by putting my JSON object, data, into an array like this:

var data: [JSON] = []

and using the following code:

self.data = self.data + JSON["content"].arrayValue
Chargeable answered 25/5, 2015 at 9:57 Comment(0)
G
9

As you said, swiftyJSON does not have an append functionality.

What you can do is parse the swiftyJSON objects into an array of type anyObject and append them.

let json = JSON(data: data!) 
var JSONObject = JSON(json["content"].arrayObject! + json["content"].arrayObject!)

Data -> NSData Object received from a HTTP request.

Gilley answered 24/5, 2015 at 23:32 Comment(0)
H
6
extension JSON {
    mutating func merge(other: JSON) {
        for (key, subJson) in other {
            self[key] = subJson
        }
    }

    func merged(other: JSON) -> JSON {
        var merged = self
        merged.merge(other: other)
        return merged
    }
}
Harpist answered 11/5, 2016 at 4:33 Comment(1)
Perfect in Swift 4. Thank you.Envisage
A
3

I liked the answer of @user2215977, but I also needed merging of nested JSONs. I extended the extension to merge nested JSONs and arrays, whereas arrays containing JSONs aren't merged, but are both in the array of the newly generated JSON.

import SwiftyJSON

extension JSON {
    mutating func merge(other: JSON) {
        if self.type == other.type {
            switch self.type {
                case .dictionary:
                    for (key, _) in other {
                        self[key].merge(other: other[key])
                    }
                case .array:
                    self = JSON(self.arrayValue + other.arrayValue)
                default:
                    self = other
            }
        } else {
            self = other
        }
    }

    func merged(other: JSON) -> JSON {
        var merged = self
        merged.merge(other: other)
        return merged
    }
}

In order to illustrate the usage I'll post my tests for this extension as well.

import XCTest
import SwiftyJSON

class JSONTests: XCTestCase {
    func testPrimitiveType() {
        let A = JSON("a")
        let B = JSON("b")
        XCTAssertEqual(A.merged(other: B), B)
    }

    func testMergeEqual() {
        let json = JSON(["a": "A"])
        XCTAssertEqual(json.merged(other: json), json)
    }

    func testMergeUnequalValues() {
        let A = JSON(["a": "A"])
        let B = JSON(["a": "B"])
        XCTAssertEqual(A.merged(other: B), B)
    }

    func testMergeUnequalKeysAndValues() {
        let A = JSON(["a": "A"])
        let B = JSON(["b": "B"])
        XCTAssertEqual(A.merged(other: B), JSON(["a": "A", "b": "B"]))
    }

    func testMergeFilledAndEmpty() {
        let A = JSON(["a": "A"])
        let B = JSON([:])
        XCTAssertEqual(A.merged(other: B), A)
    }

    func testMergeEmptyAndFilled() {
        let A = JSON([:])
        let B = JSON(["a": "A"])
        XCTAssertEqual(A.merged(other: B), B)
    }

    func testMergeArray() {
        let A = JSON(["a"])
        let B = JSON(["b"])
        XCTAssertEqual(A.merged(other: B), JSON(["a", "b"]))
    }

    func testMergeNestedJSONs() {
        let A = JSON([
            "nested": [
                "A": "a"
            ]
        ])

        let B = JSON([
            "nested": [
                "A": "b"
            ]
        ])

        XCTAssertEqual(A.merged(other: B), B)
    }
}
Afterdamp answered 17/11, 2016 at 13:31 Comment(0)
C
1

Victor's answer didn't work for me. But I solved the question by putting my JSON object, data, into an array like this:

var data: [JSON] = []

and using the following code:

self.data = self.data + JSON["content"].arrayValue
Chargeable answered 25/5, 2015 at 9:57 Comment(0)
M
0

This is now supported in SwiftyJSON.

myJson.merged(with: otherJson)

You can see examples of this in their merge tests

https://github.com/SwiftyJSON/SwiftyJSON/blob/8bbb74eec7366de10f78a05fc9dff588337c117e/Tests/SwiftJSONTests/MergeTests.swift

Merry answered 10/5, 2020 at 14:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.