0
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

BostonMacOSX
  • 1,369
  • 2
  • 17
  • 38
  • 1
    do `tempJSON.enumerated()` or simply just do `for item in tempJSON{ print(item)` <-- this won't give you the index, if you want the **index** then you must do use `enumerated()` – mfaani Mar 15 '17 at 02:21
  • I'm sorry not sure how to do enumerated in swiftyjson – BostonMacOSX Mar 15 '17 at 02:26
  • Possible duplicate of [swift for loop: for index, element in array?](http://stackoverflow.com/questions/24028421/swift-for-loop-for-index-element-in-array) – mfaani Mar 15 '17 at 02:49
  • Why does it not working? it working fine for me, dont need `enumerated()` since its `(key,value)` pair, not `(index,value)` pair – Tj3n Mar 15 '17 at 02:49

4 Answers4

1

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)
    }
}
chengsam
  • 7,315
  • 6
  • 30
  • 38
  • @BostonMacOSX I have tried using a string and it worked for me. Try to check if your user defaults is returning the correct string. – chengsam Mar 15 '17 at 03:15
0

Just do:

for(key,value) in tempJSON.enumerated(){
   print(key)
}
mfaani
  • 33,269
  • 19
  • 164
  • 293
  • Don't need enumerated for printing JSON object, his code is correct, problem maybe lying elsewhere – Tj3n Mar 15 '17 at 02:54
0

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"))
Tj3n
  • 9,837
  • 2
  • 24
  • 35
0

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)
BostonMacOSX
  • 1,369
  • 2
  • 17
  • 38