ios - (Swift3) Can return the full JSON file but I cannot return a specific value, what am I doing incorrectly? -
i have local json file named such: testthejson.json
{"myjson": [{ "id1" : {"name":"stack", "lastname": "overflow" }, "id2" : {"name":"cat", "last":"dog", } } ] }
and try read in file such:
func parsejson() { let path = bundle.main.path(forresource: "testthejson", oftype: "json") let jsondata : nsdata = nsdata(contentsoffile: path!)! nsdata! let readablejson = json(data: jsondata data, options: jsonserialization.readingoptions.mutablecontainers, error: nil) var name = readablejson["myjson","id1","name"] print(readablejson) //returns full json script print (name) //returns null }
why print(readablejson)
return full json file , print(name)
return null? doing var name = readablejson["myjson","id1","name"]
line incorrectly? thanks!
edit: using swiftyjson framework - json method from. following tutorial: https://www.youtube.com/watch?v=_nfijt6mt6a
you correctly reading in contents of testthejson.json file , asking swiftyjson parse it. (your code makes rather poor use of nsdata class, that's not causing go wrong.)
the problem testthejson.json file not valid json. therefore parse fails , nil
returned — correct behavior. therefore, nothing wrong. want parser fail when handed invalid data.
that answers question, bonus, give valid version of file:
{"myjson": [{ "id1" : {"name":"stack", "lastname": "overflow" }, "id2" : {"name":"cat", "last":"dog" } } ] }
do see difference? (hint: it's after "dog"
.)
after that, can fix subscripted expression, wrong. should be:
let name = readablejson["myjson"][0]["id1"]["name"]
or can write as:
let name = readablejson["myjson",0,"id1","name"]
Comments
Post a Comment