2

I have a JSON object:

var x: JSON = JSON([:])
x["1"].intValue = 1                      //Correct
x["2"].arrayValue = [JSON("2")]          //Error
x["3"].dictionaryValue = [3:JSON("3")]   //Error

I am able to assign an integer to x, but I am not able to assign any JSON array or any JSON dictionary. What am I doing wrong and how do I solve it?

3 Answers 3

2

Assuming you originally wanted to assign an array of JSON objects:

// doesnt work
x["1"].arrayObject = [ JSON( ["1" : "2"] ), JSON( [ "3" : "4" ] )

Try this:

x["1"] = JSON( [ JSON( ["1" : "2"]), JSON( ["3" : "4"] ) ] )

Or:

x["1"] = [ JSON( ["1" : "2"]).object, JSON( ["3" : "4"] ).object ]

Should work at least for SwiftyJSON 2.3

Sign up to request clarification or add additional context in comments.

Comments

0

As of today, the SwiftyJSON README.md tells you to use

json.array = [1,2,3,4]

but actually take a look at SwiftyJSON.swift under MARK: - Array, extension JSON. array and arrayValue are get only, you should instead use

json.arrayObject = [1,2,3,4]

which works if the array elements are native types. If you would like to assign a [JSON] to a JSON, that is, an array of JSON objects to a new JSON object try this

// Patch SwiftyJSON to support constructing a JSON out of [JSON]
extension JSON {
    public init(_ jsonArray:[JSON]) {
        self.init(jsonArray.map { $0.object })
    }
}

and thus

json["subarray"] = JSON(someArrayOfJSON)

Comments

-1

Try this:

var x = JSON([:])

x["1"] = 1
x["2"] = [2]
x["3"] = ["3":4]

println(x)

9 Comments

Hi. The example that I gave is not the exact code I am working on. I want to put a JSON array in the JSON object and I am looking for a way to do that. The above is just an example of what I am trying to achieve.
@Rishi Just assign the array like x["2"] = [2,3,4,5], isn't this working?
It works. But that is an array. I want to assign a JSON array.
@Rishi I'm kind of confused. What is exactly a JSON array?
@Rishi After x["2"] = [2,3,4,5], we can print x and see the array printed in the json. That doesn't mean it's now a JSON array?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.