【问题标题】:Parse JSON object within JSON array? [duplicate]在 JSON 数组中解析 JSON 对象? [复制]
【发布时间】:2017-07-22 08:50:48
【问题描述】:

我有以下 JSON 数据:

{
    "data":[
        {"date":"2017-07-14","value":2459.27},
        {"date":"2017-07-13","value":2447.83},
        {"date":"2017-07-12","value":2443.25},
        {"date":"2017-07-11","value":2425.53},
        {"date":"2017-07-10","value":2427.43},
        {"date":"2017-07-07","value":2425.18},
        {"date":"2017-07-06","value":2409.75},
        {"date":"2017-07-05","value":2432.54},
        {"date":"2017-07-03","value":2429.01}
    ],
    "identifier":"$SPX",
    "item":"close_price",
    "result_count":9,
    "page_size":100,
    "current_page":1,
    "total_pages":1,
    "api_call_credits":1
}

如何使用 Swift 3 访问(“解析”)值(2459.27、2447.83、2443.25、...)?

【问题讨论】:

    标签: arrays swift object


    【解决方案1】:

    你可以试试这个代码:

    // 1. Access yourJSON ["data"] only if you have ensured that the data type of yourJSON["data"] is correct as you have envisioned.
    if let dataArray = yourJSON["data"] as? [[String : Any]] {
    
        // 2. Execute a loop (for-in) to access each element of the array.
        for element in dataArray {
    
            // 3. Make sure that the "value" key of each element is of Double (or Float) type.
            if let value = element["value"] as? Double {
                print(value)
            }
        }
    }
    

    您可以参考以下文档:Collection TypesOptional Binding

    【讨论】:

      【解决方案2】:

      请试试这个:

      let aData = yourResponse["data"]
              print(aData)
      
              for aValue in aData!{
      
                  print(aValue["value"])
              }
      

      希望对你有所帮助。

      【讨论】:

        【解决方案3】:

        你可以使用这样的东西..

        var dataValues:[[String:AnyObject]] = []
        var valuesArray = [String]()
        

        然后在你的函数内部

        self.dataValues = result?["data"] as! [[String:AnyObject]]
        for fields in self.dataValues { 
           valuesArray.append(fields["value"] as! String)
        }
        
        print("Your value array ", valuesArray)
        

        【讨论】:

          猜你喜欢
          • 2011-08-04
          • 1970-01-01
          • 2015-06-02
          • 2016-05-31
          • 2014-12-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-07
          相关资源
          最近更新 更多