如何快速过滤仅包含某些键值对的json数组?
我的数组如下:
[{
"status" : "true",
"score" : "3",
"correct" : "3",
"chapter" : "34",
"answer" : "342432",
"solutionText" : "abcd",
}, {
"status" : "true",
"score" : "0",
"correct" : "2",
"chapter" : "35",
"answer" : "35854",
"solutionText" : "abc",
}]
我想获取仅包含status
,chapter
和correct
键值对的json输出数组。
赞:
[{
"status" : "true",
"correct" : "3",
"chapter" : "34",
}, {
"status" : "true",
"correct" : "2",
"chapter" : "35",
}]
答案 0 :(得分:1)
考虑到这是您的JSON
var myJSON = """
[{
"status" : "true",
"score" : "3",
"correct" : "3",
"chapter" : "34",
"answer" : "342432",
"solutionText" : "abcd"
}, {
"status" : "true",
"score" : "0",
"correct" : "2",
"chapter" : "35",
"answer" : "35854",
"solutionText" : "abc"
}]
"""
只需创建一个Decodable
struct
typealias MyArray = [MyObject] // Use this to decode
struct MyObject: Codable {
let status, correct, chapter: String
}
并像这样使用它
//Usage
var myJSONData = myJSON.data(using: .utf8)! // converting the JSON to data
let objArray = try! JSONDecoder().decode(MyArray.self, from: myJSONData) // decoding the json data into an object
//how to access
print(objArray.count)// number of elements in my array
print(objArray.first!) // getting the first object
let myObject = obj[0] // also getting the first object by index
myObject.chapter
myObject.correct
myObject.status
了解有关Codable
here的信息。
答案 1 :(得分:0)
如果它已经存在于对象中,则可以尝试
filteredArray = myArray.map { ["status": $0.status, "correct": $0.correct, "chapter": $0.chapter] }
答案 2 :(得分:0)
您可以尝试
do {
let res = try JSONDecoder().decode([Root].self, from:data)
}
catch {
print(error)
}
struct Root: Codable {
let status, correct, chapter: String
}
更正json
[{
"status" : "true",
"score" : "3",
"correct" : "3",
"chapter" : "34",
"answer" : "342432",
"solutionText" : "abcd"
}, {
"status" : "true",
"score" : "0",
"correct" : "2",
"chapter" : "35",
"answer" : "35854",
"solutionText" : "abc"
}]
更适合制作
状态为布尔值而不是字符串
正确且章节为整数
所以json看起来像
[{
"status" : true,
"score" : "3",
"correct" : 3,
"chapter" : 34,
"answer" : "342432",
"solutionText" : "abcd"
}, {
"status" : true,
"score" : "0",
"correct" : 2,
"chapter" : 35,
"answer" : "35854",
"solutionText" : "abc"
}]
您还可以根据需要设置其他值,那么您的模型将如下所示:
struct Root: Codable {
let status: Bool
let correct, chapter: Int
}
编辑:
let data = try content.rawData() // this inside do block
其中content
的类型为JSON
答案 3 :(得分:-1)
快速尝试Decodable
class MyObjectsClass : Decodable {
var objects : [Objects]?
}
class Objects : Decodable {
var status : String?
var correct : String?
var chapter : String?
}
解码时
let decodedValue = try? JSONDecoder.decode(MyObjectsClass.self, from : data)
// where data from API calls