【问题标题】:How To Filter JSON data parser如何过滤 JSON 数据解析器
【发布时间】:2018-07-07 19:43:25
【问题描述】:

JSON 响应 转Arr

[{

"total_amt" : -10000,
"tran_type" : "C3",
"pay_type" : "05",
"tran_time" : "20180125 133122",
"point_total" : 0
 },

 {

"total_amt" : -1004,
"tran_type" : "C5",
"pay_type" : "05",
"tran_time" : "20180124 163602",
"point_total" : 0
}]

======================

我要过滤 tran_type = "C3"

我该怎么办?

"total_amt" : -10000,
"tran_type" : "C3",
"pay_type" : "05",
"tran_time" : "20180125 133122",
"point_total" : 0

【问题讨论】:

  • “我该怎么办?”在顶部找到一个搜索框,然后按照自己的方式进行操作。
  • json.filter { return $0["tran_type"] as? String == "C3" } 反正这样的东西不是一个有效的数据结构,你应该用[} 替换{]
  • 感谢您的帮助。 :)

标签: json swift swift3 filter alamofire


【解决方案1】:

试试这样的:

let string = "[{ \"total_amt\" : -10000,\"tran_type\" : \"C3\", \"pay_type\" : \"05\", \"tran_time\" : \"20180125 133122\", \"point_total\" : 0},{\"total_amt\" : -1004,\"tran_type\" : \"C5\", \"pay_type\" : \"05\", \"tran_time\" : \"20180124 163602\", \"point_total\" : 0 }]"

// Convert string to Data
let jsonData = string.data(using: .utf8)!

do {
    // Serialize the json Data and cast it into Array of Dictionary
    let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [[String: Any]]

    // Apply filter on `tran_type`
    let tranArr = jsonObject?.filter({ (dictionary) -> Bool in
        dictionary["tran_type"] as? String == "C3"
    })

    print(tranArr)

} catch {
    print(error)
}

过滤后的结果将在tranArr 对象中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多