如何使用Swift在此JSON字典中访问特定值?

时间:2018-10-12 22:01:35

标签: json swift api

我正在尝试从该API(Tracker Network API)中获取总的获胜金额,我已经获取了密钥,并且它会像这样显示密钥和值。

enter image description here

代码在下面,我还可以获取获胜次数(Integer)以及这些值(标题)。但是,我无法弄清楚如何仅获得“胜利数”而不将所有其他数字也打印出来。

我尝试过

print(statsArray[8])
 totalWins = statsArray[8]
 //["value": 4350, "key": Wins]
 print(totalWins.values)
 //[Wins, 4350]

,但它不会按照我希望的方式打印。我希望将其作为数字打印出来,以便随后将其加载到UILabel中。

我要问的是,我如何仅打印“ Wins”(整数)金额而不打印其他11个json输出?我只想要一个数字。

let epicName = "Ninja"
let formattedName = epicName.replacingOccurrences(of: " ", with: "%20")                   
let platform = "pc"
//pc, xbl, psn


let fortniteChallengesURL3 = URL(string: "https://api.fortnitetracker.com/v1/profile/\(platform)/\(formattedName)")
if let unwrappedURL = fortniteChallengesURL3 {
var request = URLRequest(url: unwrappedURL)
request.addValue("MyKey", forHTTPHeaderField: "TRN-Api-Key")
let dataTask = URLSession.shared.dataTask(with: request) { (data, response, error) in

    if let data = data {
        do {
            let json = try JSONSerialization.jsonObject(with: data) as! [String:Any]
            //print(json)



            for (key, value) in json {


                if (key == "lifeTimeStats") {
                    if let statsArray:[ [String : Any] ] = value as? [ [String : Any] ] {

                        //accessing the 8th but I am getting the output wrong
                        /*let firstKey = Array( (value as? [ [String : Any] ])!)[8]
                        */

                        print(statsArray[8])
                        let totalWins = statsArray[8]
                        //["value": 4350, "key": Wins]
                        print(totalWins.values)
                        //[Wins, 4350]

                        for dict in statsArray {
                            for (key, value) in dict {

                                if (key == "key") {
                                    //print ( "\(firstKey.values)")

                                    print ( "keys are     \(value)")


                                }
                                /*if (key == "value") {
                                    print ( "value are     \(value)")


                                }*/
                            }
                        }

                    }


                }

            }



        } catch let error as NSError {
            print(error.localizedDescription)

            DispatchQueue.main.asyncAfter(deadline: .now() ) {

            }
        }
    }
}
dataTask.resume()
}

2 个答案:

答案 0 :(得分:0)

当您遍历字典数组中的每个项目时,可以像这样直接访问键和值字段:

for dic in statsArray {
     let title = dic["key"]
     let value = dic["value"] // You can use this as the value for the label
}

如果您只想访问总获胜数据,则可以执行以下操作:

let totalWinsValues = totalWins["value"]

您将要考虑以类的结构形式创建数据模型,并实现Codable协议以使事情变得更容易和更清洁。

答案 1 :(得分:0)

TotalWins是具有两个项目的字典,您可以通过其键访问字典中的任何项目值,因此请尝试以下操作:

print(totalWins["value"])