2017-07-30 64 views
0

我想從以下JSON提取第一「字段1」「字段2」值來取出第一個重複元素嵌套的JSON:如何使用SWIFT 3

{ 
"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" 
    } 
] 
} 

我有以下工作代碼打印兩種進料的文字:當我嘗試提取第一饋送進入

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) 
然而

,我嘗試不活像ķ。

我已經試過:

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

道歉,如果此之前已被覆蓋,我看着堆棧溢出幾個類似的問題,但不能使其適應我的情況。

+0

因爲'feed'的類型是'Any'。將其轉換爲數組:let feeds = json [「feeds」] as! [[String:AnyObject]]' –

+0

[type any?沒有下標成員](https://stackoverflow.com/questions/38956785/type-any-has-no-subscript-members) – vadian

回答

0

由於json類型爲Any,因此需要將其轉換爲更具體的類型,即字典數組。

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 
     } 
    } 
}