Reputation: 1461
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
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
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
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