Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a JSON which contains an array inside a json Object without a arrayName [closed]

Tags:

swift

swift3

I get a JSON array like this

[
{
"accNo":"8567856",
"ifscCode":"YESB000001"
},
{
"accNo":"85678556786",
"ifscCode":"YESB000001"
}
]

I get an array with no arrayName in json. I tried to parse this JSON in swift 3 with type casting it to get the values in all array(using as? NSArray, NSDictionary, [Array -String,AnyObject-],etc).But it all failed. Is there a way in swift to get array values

like image 873
Jeesson_7 Avatar asked Jun 25 '26 12:06

Jeesson_7


2 Answers

You may want to check SwiftyJSON but here's your answer using Foundation.

Swift 4:

let str = """
[
{
"accNo":"8567856",
"ifscCode":"YESB000001"
},
{
"accNo":"85678556786",
"ifscCode":"YESB000001"
}
]
"""

let data = str.data(using: .utf8)!

do {

    let json = try JSONSerialization.jsonObject(with: data) as? [[String:String]]

    for item in json! {

        if let accNo = item["accNo"] {
            print(accNo)
        }

        if let ifscCode = item["ifscCode"] {
            print(ifscCode)
        }
    }

} catch {
    print("Error deserializing JSON: \(error)")
}
like image 199
Anushk Avatar answered Jun 27 '26 08:06

Anushk


Use JSONSerialization to convert data to an array of Dictionary of Strings, [[String:String]].

let str = """
[
{
"accNo":"8567856",
"ifscCode":"YESB000001"
},
{
"accNo":"85678556786",
"ifscCode":"YESB000001"
}
]
"""
let data = str.data(using: .utf8)!
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [[String:String]]
print(json) // [["accNo": "8567856", "ifscCode": "YESB000001"], ["accNo": "85678556786", "ifscCode": "YESB000001"]]
like image 22
Puneet Sharma Avatar answered Jun 27 '26 08:06

Puneet Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!