[Solved] filter array of json in swift


Considering this is your 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"

    }]
"""

Simply create a Decodable struct like this

typealias  MyArray = [MyObject] // Use this to decode 

struct MyObject: Codable {
    let status, correct, chapter: String
}

And use it like this

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

Read about Codable here .

6

solved filter array of json in swift