BostonAreaHuman
BostonAreaHuman

Reputation: 1461

How can I loop through an object in SwiftyJSON? not just with swift

var tempJSON:JSON = ""
tempJSON = JSON(self.userdefaults.string(forKey: "currentOrder"))
print(tempJSON)

yields:

{"7": "1", "21": "0", "20": "0", "3": "1"}

I need to be able to loop through this and just can't. I've tried.

for(key,value) in tempJSON{
       print(key)

            }

and nothing outputs....

Thanks

Upvotes: 0

Views: 684

Answers (4)

BostonAreaHuman
BostonAreaHuman

Reputation: 1461

SOLUTION I had to add the parseJSON: to the JSON method so as to tell that is was coming from a string literal.

var tempJSON:JSON = ""
tempJSON = JSON(parseJSON: self.userdefaults.string(forKey: "currentOrder"))
print(tempJSON)

Upvotes: 0

chengsam
chengsam

Reputation: 7405

Try getting Data from the string and use it to init the JSON object:

let jsonString = "{\"7\": \"1\", \"21\": \"0\", \"20\": \"0\", \"3\": \"1\"}"
if let dataFromString = jsonString.data(using: .utf8, allowLossyConversion: false) {
    let tempJSON = JSON(data: dataFromString)
    print(tempJSON)

    for (key, value) in tempJSON {
        print(key)
        print(value.stringValue)
    }
}

Upvotes: 1

Tj3n
Tj3n

Reputation: 9923

My best guess is that you are getting a string out from your userdefault and use it to init JSON, try change:

tempJSON = JSON(self.userdefaults.string(forKey: "currentOrder"))

to

tempJSON = JSON(self.userdefaults.dictionary(forKey: "currentOrder"))

Upvotes: 0

mfaani
mfaani

Reputation: 36297

Just do:

for(key,value) in tempJSON.enumerated(){
   print(key)
}

Upvotes: 0

Related Questions