简体   繁体   中英

How to pull first repeating element in nested JSON using SWIFT 3

I'm trying to extract the first "Field1" and "Field2" values from the following JSON:

{
"channel": {
    "id": 297681,
    "name": "Basement",
    "description": "Climate Node Upstairs",
    "latitude": "0.0",
    "longitude": "0.0",
    "field1": "Temperature",
    "field2": "Humidity",
    "created_at": "2017-07-04T21:43:23Z",
    "updated_at": "2017-07-30T16:52:48Z",
    "last_entry_id": 17803
},
"feeds": [
    {
        "created_at": "2017-07-30T16:50:46Z",
        "entry_id": 17802,
        "field1": "68.18",
        "field2": "53.80"
    },
    {
        "created_at": "2017-07-30T16:52:48Z",
        "entry_id": 17803,
        "field1": "68.18",
        "field2": "53.90"
    }
]
}

I have the following working code which prints the text of the two feeds:

  let url = URL(string: "https://api.thingspeak.com/channels/297681/feeds.json?api_key=xxxx&results=2")!

    let task = URLSession.shared.dataTask(with: url)
    {
        (data, response, error)
        in
        if let data = data, let rawJSON = try? JSONSerialization.jsonObject(with: data, options:.allowFragments) as? [String: Any]
        {
            print ("rawjason set")

            if let json = rawJSON as? [String: Any]
            {
                //print(json) //should print json
                //  print("<-------->`")
                //  print(json["channel"])
                let channel = json["channel"] as! [String: Any]
                // print(channel["name"]!)

                //let locname = channel["name"]! as! [String: String]
                let locname = channel["name"]!
                print("<-- name next -->")
                print(locname)


                let feeds = json["feeds"]
                print("<feeds>")
                print(feeds)

however when I try to extract the first feed entry, what I'm trying doesn't work.

I've tried:

//fails with Type Any> has no subscript members:
let feed1 = feeds[0]

Apologies if this has been covered before, I looked at several similar questions on Stack overflow but could not adapt them to my situation.

Since json is of type Any , you need to cast it to a more specific type, namely an array of dictionaries.

if let feeds = json["feeds"] as? [[String:Any]] {
    for feed in feeds {
        if let field1 = feed["field1"] as? Double {
            //do whatever you need to with field1
        }
        if let field2 = feed["field2"] as? Double {
            //do whatever you need to with field2
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM