Sami Sami - 1 month ago 9
iOS Question

(Swift3) Can return the full JSON file but I cannot return a specific value, what am I doing incorrectly?

I have a local JSON file named as such: testTheJSON.json

{"myJSON":
[{
"ID1" :
{"name":"Stack",
"LastName": "Overflow"
},
"ID2" :
{"name":"Cat",
"last":"dog",
}
}
]
}


and I try to read in the file as such:

func parseJSON() {
let path = Bundle.main.path(forResource: "testTheJSON", ofType: "json")
let jsonData : NSData = NSData(contentsOfFile: path!)! as NSData!
let readableJSON = JSON(data: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil)
var name = readableJSON["myJSON","ID1","name"]
print(readableJSON) //returns the full JSON script
print (name) //returns null
}


Why does
print(readableJSON)
return the full JSON file and
print(name)
return as null? Am I doing the
var name = readableJSON["myJSON","ID1","name"]
line incorrectly? Thanks!

EDIT: I am using the SwiftyJSON framework - this is where the JSON method is from. I was following this tutorial: https://www.youtube.com/watch?v=_NfijT6mt6A

Answer

You are correctly reading in the contents of your testTheJSON.json file and asking SwiftyJSON to parse it. (Your code makes some rather poor use of the NSData class, but that's not actually causing anything to go wrong.)

The problem is that your testTheJSON.json file is not valid JSON. Therefore the parse fails and nil is returned — which is actually correct behavior. Therefore, nothing is wrong. We want the parser to fail when it is handed invalid data.

That actually answers the question, but as a bonus, I will also give you a valid version of your file:

{"myJSON":
[{
 "ID1" :
    {"name":"Stack",
    "LastName": "Overflow"
    },
 "ID2" :
    {"name":"Cat",
    "last":"dog"
    }
 }
 ]
}

Do you see the difference? (Hint: it's after "dog".)

After that, you can fix your subscripted expression, which is currently wrong. It should be:

let name = readableJSON["myJSON"][0]["ID1"]["name"]

Or you can write it as:

let name = readableJSON["myJSON",0,"ID1","name"]