I have below json object. i am parsing json and storing this as disctionary. now i want to get these array from disctionary but when i am using objectForKey("upcomingAppointments") it given me nothing
{
"upcomingAppointments": [],
"upcomingFollowUps": [],
"followUps": []
}
Try this:
var dictionary = //NSDictionary from somewhere...
if let upcomingAppointments = dictionary["upcomingAppointments"] as? NSArray {
//Process your appointments here.
}
//Same goes for other such json fields.
Related
I have a very large JSON file that I have downloaded from the web, and I need to parse this in Swift. The JSON construction is an array of dictionaries. Each dictionary object contains a key of "phone" (referring to the phone number), and whose value is the actual phone number in the form of a string.
What I would like to do, is iterate through the entire list of dictionary objects in the array, and ensure that there are no dictionary objects that have the same value for the key, "phone". If a duplicate is found, I would like to eliminate it from the list, and print it out to the console.
Here is the relevant code that I have:
guard let json = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
print("error")
return
}
for dict in json! {
//This is where I would do the check
}
How would I accomplish this?
You can do as
var ph = [String]()
var newjson = [[String:String]]()
for dict in json {
if ph.contains(dict["Phone"]!) {
print("duplicate phone \(dict["Phone"]!)")
} else {
ph.append(dict["Phone"]!)
newjson.append(dict)
}
}
print(newjson)
Hare newjson is the new array of dictionary that do not have duplicate phone
Use the array extension method to remove the duplicates from the json object
extension Array where Element: Equatable {
mutating func removeDuplicates() {
var result = [Element]()
for value in self {
if !result.contains(value) {
result.append(value)
}
}
self = result
}
}
Alamofire.request(apiURL, method: .get, parameters:parameters, headers:headers)
.responseJSON { response in
if let result = response.result.value {
let json = JSON(result)
var listArray = json["somekey"].arrayValue
listArray.removeDuplicates()
print(listArray)
}
}
I have this subJSON["guestpics"] as JSON data from SwiftyJSON.
When I print(subJSON["guestpics"]) I have this:
[
"/images\/profile_pic\/1.jpg",
"/images\/profile_pic\/2.jpg",
"/images\/profile_pic\/3.jpg"
]
How can I convert this to an array ?
for (_, subJSON): (String, JSON) in json[0]["data"] {
print(subJSON["guestpics"])
}
SwiftyJSON has already parsed your JSON data and prepared typed objects.
If the key subJSON["guestpics"] contains an array, then use SwiftyJSON's optional getter .array to get it:
if let guestPicsArray = subJSON["guestpics"].array {
// here "guestPicsArray" is your array
}
Why not directly storing the value of the key in the array? as it look like array
Does it show any error/crash when you are trying to store ?
if let arrGuest = subJSON["guestpics"] as? Array<String> {
}
Or if you are more familiar with Objective-c
if let arrGuest = arr as? NSArray {
}
you can get the array in the arrGuest object
I try to get json data from web site, however, I can access to json data as the following.
{
"product_categories":[
{
"id":27,
"name":"Clothing",
"slug":"product-categories-1",
"parent":0,
"description":"",
"count":3
}
]
}
On the other hand, when I try to get json data as below,
{
"product":{
"title":"Night Cream",
"id":4573,
"created_at":"2015-08-21T07:54:09Z",
"updated_at":"2015-08-27T01:37:06Z",
}
}
there is on jason data response back “[]”
I am using Alamofire to get data. Here is my code.
Alamofire.request(.GET, url).responseJSON {
(request, response, json, error) in
if json != nil {
var jsonObj = JSON(json!)
if let data = jsonObj["product"].arrayValue as [JSON]? {
self.productsAll = data
self.collectionView!.reloadData()
}
How can I get all of product data. Please advise. Thank you.
you are trying to cast a json object to a json array, which means your conditional unwrapping will never execute.
replace
if let data = jsonObj["product"].arrayValue as [JSON]? {
self.productsAll = data
self.collectionView!.reloadData()
}
with
if let data = jsonObj["product"].dictionaryObject {
// since self.productsAll seems to be an array, append the product to the array or rebuild the array before calling self.collectionView!.reloadData()
}
[
{
"ID": 0,
"Name": "PHI"
},
{
"ID": 0,
"Name": "ATL"
}
]
I'm using SwiftyJSON and Alamofire. This is what is being returned. I want to loop through each of these objects now in my code. I'm having trouble getting this information though.
json[0]["Name"].string seems to return nil, and I'm not sure why. The JSON object is definitely getting the JSON, when I print it to the console it looks exactly like above.
I also tried:
var name = json[0].dictionary?["Name"]
Still nil though.
Any ideas?
EDIT
Here's the code I'm using to retrieve the JSON.
Alamofire.request(.GET, "url", parameters: nil, encoding: .JSON, headers: nil).responseJSON
{
(request, response, data, error) in
var json = JSON(data!)
//var name = json[0].dictionary?["Name"]
}
Your JSON is valid (at least this snippet is), and your first method to retrieve the data from SwiftyJSON is correct.
On the other hand, the Alamofire snippet you showed didn't compile for me, I had to change the signature.
Given that in the comments you say that not only json[0]["Name"] is nil but json[0] is also nil, I think you have a problem with how your data is fetched.
I tested this version of the Alamofire method in a sample app and it worked well:
Alamofire.request(.GET, yourURL).responseJSON(options: nil) { (request, response, data, error) in
let json = JSON(data!)
let name = json[0]["Name"].string
println(name)
}
In the screenshot, the URL is my local server, with your JSON copy pasted in "test.json".
This "answer" is an extension of my comment, I needed room to show more info...
I think you might try this.
first convert JSON(data) using swifyJSON
let json = JSON(data!)
then count the array element in data.
let count: Int? = json.array?.count
after that use for loop to reach array element one.
for index in 0...count-1 {
self.idArray.append(json[index]["ID"].stringValue)
self.nameArray.append(json[index]["Name"].stringValue)
}
you will get sorted data in "idArray" and "nameArray". try to print both the array.
You do not have to use index to parse array. You can get single json object from array and use it to access the data:
for (index: String, subJson: JSON) in json {
println("Current Index = \(index)")
if let _id = subJson["ID"].int {
println("ID = \(_id)")
} else {
println("Error ID")
}
if let _name = subJson["Name"].string {
println("Name = \(_name)")
} else {
println("Error Name")
}
}
I'm trying to read a json array data as below with my code but I'm getting empty result all the time while I can print the whole data. Please where would be my issue?
I've read this topic but I couldn't get the result. Topic Link
{"Cars":[{"Brand":"Alfa Romeo"},{"Brand":"Audi"},{"Brand":"BMW"},{"Brand":"Citroen"},{"Brand":"Dacia"},{"Brand":"Fiat"},..........
My code
func getData(){
var url = "http://test.net/services/test.php"
var request = HTTPTask()
request.GET(url, parameters: nil, completionHandler:
{
(response:HTTPResponse) in
var jsonData = response.responseObject as! NSData
var json = JSON(data: jsonData)
println("All data \(json)")
dispatch_async(dispatch_get_main_queue(),
{
println(json["Cars"]["Brand"].stringValue)
})
})
}
json["Cars"] is an array, so for example to get the first item via SwiftyJSON:
println(json["Cars"][0]["Brand"].stringValue)
In a JSON string, { and } are delimiters for dictionaries, whereas [ and ] are delimiters for arrays.
EDIT:
Following your comment, yes, you can loop over the array:
if let cars = json["Cars"].array {
for car in cars {
println(car["Brand"])
}
}
This way you can get your json objects using SwiftyJSON:
//Get your Data First
let json = JSON(data: data)
//Store your values from car key into Car object so we can get total count.
let Cars = json["Cars"].arrayValue
//Use For loop to get your car Brand
for i in 0..<Cars.count
{
println(json["Cars"][i]["Brand"].stringValue)
}
And your output will be:
Alfa Romeo
Audi
BMW
Citroen
Dacia
Fiat
Hope this is what you need.