Jacobi
Jacobi

Reputation: 21

Accessing JSON data with Swift

I have an array of JSON data from the following call:

guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [Any] else {
print("Not containing JSON")
return
}

when I run print(json) I get the following in the output:

[{
"CREATED_BY" = "DOMAIN\\USER";
"CREATED_DATE" = "2016-11-28T08:43:59";
STATUS = U;
"WIDGET_NUMBER" = K11;
"UPDATED_BY" = "<null>";
"UPDATED_DATE" = "<null>";
}, {
"CREATED_BY" = "DOMAIN\\USER";
"CREATED_DATE" = "2016-05-09T08:46:23";
STATUS = U;
"WIDGET_NUMBER" = 89704;
"UPDATED_BY" = "<null>";
"UPDATED_DATE" = "<null>";
}]

I am trying to get all of the WIDGETNUMBER values in the array of JSON data. The json variable is a Any type and I have not been able to convert to a struct so far. Is there an easy way to get the elements from the JSON objects?

Upvotes: 0

Views: 2132

Answers (4)

Abizern
Abizern

Reputation: 150565

If you just want an array of widget numbers you could use the reduce function which iterates the dictionaries in the array and extracts the widget numbers:

Using your data I put this in a storyboard:

let json = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as! [[String: Any]]

let widgetNumbers = json?.reduce(into: [String]()){ (accum, dict) in
    guard let widget = dict["WIDGET_NUMBER"] as? String else { return }
    accum.append(widget)
}

widgetNumbers // -> ["K11", "89704"]

Upvotes: 0

Soh
Soh

Reputation: 16

Joakim's answer is spot on for getting the widget number. For your struct, be sure to add something like this as an initializer to map your object.

let widgetNumber: Int
let user: String

    init?(json:[String:Any]) {

      guard let widgetNumber = json["WIDGET_NUMBER"] as? Int, 
            let user = json["CREATED_BY"] as? String else { return nil }

    self.widgetNumber = widgetNumber
    self.user = user

    }

Upvotes: 0

Keita Junichiro
Keita Junichiro

Reputation: 226

Your content is array of Dictionary, so that you must convert each element Dictionary to Json

for dic in content {
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: dic, options: .prettyPrinted)
        print(jsonData)
    } catch {
        print(error.localizedDescription)
    }
}

Or you can read value of WIDGET_NUMBER direct from Dictionary

for dic in content {
    print(dic["WIDGET_NUMBER"] ?? "Not found")
}

Upvotes: 0

Joakim Danielson
Joakim Danielson

Reputation: 51821

It looks like you have an array of dictionaries

for item in json {
    if let item = item as? [String: Any],  let widgetNo = item["WIDGET_NUMBER"] {
        print(widgetNo)
    }
}

Upvotes: 2

Related Questions