3

I am trying to access ["upper category"]["first category"][0][0] of local json file

{
    "upper category": {
        "first category": [
            [
                "this is a question", 
                "this is an answer", 
                "this is the rank"
            ], 
            [
                "this is a question2", 
                "this is an answer2", 
                "this is the rank2"
            ]
        ], 
        "second category": [
            [
                "this is a question3", 
                "this is an answer3", 
                "this is the rank3"
            ]
        ]
    }
}

with

let path = Bundle.main.path(forResource: "data", ofType: "json")
do {let data:NSData = try NSData(contentsOfFile: path!)
    let json = try? JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

I am not able to access anything beyond the first dictionary.

I tried several times with options like (I tried multiple older solutions but they don't seem to work for me, maybe swift 3)

    if let description = ((((json?["upper category"] as? AnyObject)?["first category"] as? AnyObject)?[0] as? AnyObject)?[0] as? String) {

It is likely a noob question, I am new to ios. While any answer extremely appreciated explaining how to write code for other number of nested types would be best

(xcode 8, swift 3)

1 Answer 1

2

It's a bit overkill but you can cast the json to [String:[String:[[String]]]]

let json = try? JSONSerialization.jsonObject(...) as? [String:[String:[[String]]]]

Otherwise, if for example, the dictionary contains elements other than a nested dictionary, you will just have to cast the top level dictionary to [String:Any] and cast the nested elements individually.

if let json = try? JSONSerialization.jsonObject(...) as? [String:Any] {

    let foo = json["foo"] as? Int
    let bar = json["bar"] as? [String:Any]

    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

What if my son object is not homogenous and only one of the element of the dictionary is a nested dictionary? I can't cast it as [String: [String: Any]]. And I cannot get a nested dictionary just as the OP
@rommex you will have to cast the nested elements individually in that case, I have updated my answer to cover this scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.