Swift - Use dictionary to pass data to params - arrays

I'm trying to pass some datas in my parameters to send to a server. But I'm facing some difficulties to build the params.
I have tried to loop through the array to add the dictionary which consists of the mobile and name but I'm not sure on how to build it properly as it return only first element of the array. I don't know how to append everything in the array.
var parameters: [String: Any] = ["invitations": [
["mobile": "1234567",
"name": "John1"]
]
]
for (item1, item2) in zip(arrName, arrNumber){
parameters = ["invitations": [
"mobile" : "\(item2)",
"name" : "\(item1)"]
]
}
This is the JSON I'm trying to build in the params.
{
"invitations": [
{
"mobile": "1234456",
"name": "Paul"
},
{
"mobile": "1234456",
"name": "Paul1"
},
{
"mobile": "1234456",
"name": "Paul2"
}
]
}

let arr = zip(arrNumber,arrName).map { ["mobile":$0,"name":$1] }
var parameters: [String: Any] = ["invitations": arr]
print(parameters)//["invitations": [["name": "Paul", "mobile": "1234456"], ["name": "Paul1", "mobile": "1234456"], ["name": "Paul2", "mobile": "1234456"]]]
do {
let json = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
let convertedString = String(data: json, encoding: .utf8)
print(convertedString)
} catch let error {
print(error.localizedDescription)
}
{ "invitations": [
{
"name": "Paul",
"mobile": "1234456"
},
{
"name": "Paul1",
"mobile": "1234456"
},
{
"name": "Paul2",
"mobile": "1234456"
} ] }

Related

How can I remove all JSON objects that have a certain key/value pair from an array of JSON objects?

I want to filter a dataset this like:
For example here's some fake dataset:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Donna",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Tia",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tuxedo"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
I want to filter out everything that has "livesInCity": false:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
How can I do this? Is this possible?
In python I believe it's something like this, but I do not know how to get started in Swift:
people = [person for person in people if person.livesInCity == True]
Also, how can I filter this data set above to look like this - I want to categorize by type in name.
{
"tabby": ["Sakura", "Linn"],
"tuxedo": ["Dora"],
}
Any help will be very appreciated!
As already mentioned in the comments, you can't work directly on JSON objects in Swift. They need to be converted first.
You can parse your JSON to a Swift object and then perform filtering, grouping etc.
struct Person: Codable {
let name: String
let hasChildren: Bool
let livesInCity: Bool
let pets: [Pet]
}
struct Pet: Codable {
let cats: [String]
let type: String
}
let jsonStr = "[{"name": "Sakura", ..." // your JSON string
let jsonData = jsonStr.data(using: .utf8)!
let parsedObjects = try! JSONDecoder().decode([Person].self, from: data)
Then you can filter your parsedObjects:
let filteredObjects = parsedObjects.filter({ person in person.livesInCity == true })
or in shorter (swiftier) version:
let filteredObjects = parsedObjects.filter { $0.livesInCity }
You can also try to group by pet type:
var groupedDict = [String:[String]]()
filteredObjects.forEach{ person in
person.pets.forEach { pet in
if let _ = groupedDict[pet.type] {
groupedDict[pet.type]!.append(person.name)
} else {
groupedDict[pet.type] = [person.name]
}
}
}
print(groupedDict)
//prints ["tabby": ["Sakura", "Linn"], "tuxedo": ["Dora"]]
If at any point you want to convert your objects back to JSON you can use:
let dictData = try! JSONEncoder().encode(groupedDict)
let dictStr = String(data: dictData, encoding: .utf8)!
print(dictStr)
//prints {"tabby":["Sakura","Linn"],"tuxedo":["Dora"]}
Note
For the sake of simplicity I used forced optional unwrapping (!) when decoding/encoding objects. You may want to use do-try-catch instead (to catch errors).

How to get JSON array value in Swift using Codable

I'm having trouble getting the direction values from the following JSON:
"routeOptions": [
{
"name": "Jubilee",
"directions": [
"Wembley Park Underground Station",
"Stanmore Underground Station"
],
"lineIdentifier": {
"id": "jubilee",
"name": "Jubilee",
"uri": "/Line/jubilee",
"type": "Line",
"routeType": "Unknown",
"status": "Unknown"
}
}
]
I believe the directions is a JSON array, which at the moment I'm using Codable as below. I've managed to get the routeOptions name but can't seem to figure out how to get the directions as there's no specific key variable. Please can someone help?
struct RouteOptions: Codable {
let name: String?
let directions: [Directions]?
init(name: String, directions: [Directions]) {
self.name = name
self.directions = directions
}}
struct Directions: Codable {}
You need to handle directions as an array of String
struct RouteOptions: Codable {
let name: String
let directions: [String]
}
Here is an example where I fixed the json to be correct
let data = """
{ "routeOptions": [
{
"name": "Jubilee",
"directions": [
"Wembley Park Underground Station",
"Stanmore Underground Station"
],
"lineIdentifier": {
"id": "jubilee",
"name": "Jubilee",
"uri": "/Line/jubilee",
"type": "Line",
"routeType": "Unknown",
"status": "Unknown"
}
}
]}
""".data(using: .utf8)!
struct Root: Decodable {
let routeOptions: [RouteOptions]
}
struct RouteOptions: Codable {
let name: String
let directions: [String]
}
do {
let result = try JSONDecoder().decode(Root.self, from: data)
print(result.routeOptions)
} catch {
print(error)
}

Create Array of Dictionaries iOS Swift

I am trying to implement an array of dictionaries but I get an output different from my expectation.
In the following code snippet I create an array, a dictionary and execute the append operation:
var MemberArray = [[String: Any]]()
let dict = ["member_status":"1",
"member_id": memid ,
"membership_number": memshpid,
"name": memname,
"mobile":memno ,
"billing":"1"] as NSDictionary
MemberArray.append(dict as! [String : Any])
I need it to be this:
[
{
"member_status": 1,
"member_id": 3,
"membership_number": "GI99010286",
"name": "Thomas",
"mobile": "9873684678",
"billing": 0
},
{
"member_status": 1,
"member_id": 5,
"membership_number": "GI99010144",
"name": "Raj",
"mobile": "9873684678",
"billing": 1
}
]
But I get the following:
[
[
"member_status": 1,
"member_id": 3,
"membership_number": "GI99010286",
"name": "Thomas",
"mobile": "9873684678",
"billing": 0
],
[
"member_status": 1,
"member_id": 5,
"membership_number": "GI99010144",
"name": "Raj",
"mobile": "9873684678",
"billing": 1
]]
How can I achieve my goal?
For that you have to serialize that array. Here data is that array :
let dataSet = try! JSONSerialization.data(withJSONObject: data, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: dataSet, encoding: String.Encoding.utf8.rawValue)!

how to get the data in array of dictionary in swift?

I want to save the subcategory data in this form [[value1,value2,...],[value1, value2],[value1],.....] in the following code
var subcategories = [SubCategory]()
for (_, item) in json {
//do something with item.id, item.name
for (_, subcategory) in item["subcategory"] {
let subcategory = SubCategory(
id: Int(subcategory ["id"].stringValue),
name: subcategory ["name"].string,
desc: subcategory ["desc"].string,
image: subcategory ["image"].string,
coupon: Int(subcategory ["coupon"].stringValue),
icon: subcategory ["icon"].string,
order: Int(subcategory ["order"].stringValue),
aname: subcategory ["aname"].string,
options: Int(subcategory ["options"].stringValue),
items: subcategory ["items"].arrayObject
)
subcategories.append(subcategory)
}
print(subcategories.count)
for sub in subcategories {
print(sub.name)
print(sub.id)
print(sub.desc)
self.SUBCATNAME.append(sub.name!)
self.SUBARRAY?.append(self.SUBCATNAME)
}
print(self.SUBCATNAME)
print(self.SUBARRAY)
}
I need to append all the subcategory name in an array of dictionary like the above structure. Here i created SUBARRAY as var SUBARRAY:[[String]] = []. but the value is coming as nil. Here i am getting the json data from Api using Swiftyjson. How to implement this??
my sample json data is as below:
like wise so many subcategories are there
[
{
"id": "244",
"name": "PIZZAS",
"subcategory": [
{
"id": "515",
"name": "MARGARITA",
"description": "Cheese and Tomato",
"image": "",
"icon": "",
"coupon": "1",
"order": "1",
"aname": "",
"options": "2"
},
{
"id": "516",
"name": "ABC",
"description": "HNDDSGHFD",
"image": "",
"icon": "",
"coupon": "1",
"order": "1",
"aname": "",
"options": "2",
},
{
"id": "516",
"name": "DEF",
"description": "HFDGFJJFHFKH",
"image": "",
"icon": "",
"coupon": "1",
"order": "1",
"aname": "",
"options": "2",
}
]
},
{
......
}
]
if you try this code
for (NSDictionary *dictionary in ArrCategory)
{
NSMutableArray *sub_cat_data=[dictionary objectForKey:#"sub_cat_data"];
for (NSDictionary *sub_cat_dict in sub_cat_data)
{
NSMutableArray *sub_cat_data=[sub_cat_dict objectForKey:#"sub_data"];
for (NSDictionary *dictionary1 in sub_cat_data)
{
NSMutableDictionary *Dic_Sub_cat=[[NSMutableDictionary alloc]init];
NSString *str_dic_id=[dictionary1 objectForKey:#"sub_id"];
NSString *str_dic_name=[dictionary1 objectForKey:#"sub_name"];
[Dic_Sub_cat setObject:str_dic_id forKey:#"sub_id"];
[Dic_Sub_cat setObject:str_dic_name forKey:#"sub_name"];
[Dic_Sub_cat setObject:#"0" forKey:#"sub_Chekid"];
[New_ArrCategory addObject:Dic_Sub_cat];
}
}
}
swift example
if let results: NSMutableArray = jsonResult["data"] as? NSMutableArray
{
var ArrMoodtype2 : NSMutableArray!
ArrMoodtype2 = NSMutableArray()
ArrMoodtype2 = results
ArrFeel = NSMutableArray()
for var i = 0; i < ArrMoodtype2.count; i++
{
var Dic : NSMutableDictionary!
Dic = NSMutableDictionary()
let tempDic: NSMutableDictionary = ArrMoodtype2[i] as! NSMutableDictionary
let strMoodCatID = tempDic ["mood_cat_id"] as! String
let strMoodID = tempDic ["mood_id"] as! String
let strMoodImage = tempDic ["mood_image"] as! String
let strMoodName = tempDic ["mood_name"] as! String
Dic.setObject(strMoodCatID, forKey: "mood_cat_id")
Dic.setObject(strMoodID, forKey: "mood_id")
Dic.setObject(strMoodImage, forKey: "mood_image")
Dic.setObject(strMoodName, forKey: "mood_name")
ArrFeel.addObject(Dic)
}
}

How to define array of arrays

I am trying to fetch the Json data from Api which is in the following format
[
{
"id": "244",
"name": "PIZZAS",
"image": "",
"coupon": "1",
"icon": "",
"order": "1",
"aname": "",
"options": "2",
"subcategory": [
{
"id": "515",
"name": "MARGARITA",
"description": "Cheese and Tomato",
"image": "",
"icon": "",
"coupon": "1",
"order": "1",
"aname": "",
"options": "2",
"item": [
{
"id": "1749",
"name": "9 Inch Thin & Crispy Margarita",
"description": "",
"price": "3.40",
"coupon": "1",
"image": "",
"options": "2",
"order": "1",
"addon": "495",
"aname": "",
"icon": ""
},
{
"id": "1750",
"name": "12 Inch Thin & Crispy Margarita",
"description": "",
"price": "5.20",
"coupon": "1",
"image": "",
"options": "2",
"order": "2",
"addon": "496",
"aname": "",
"icon": ""
}
]
}
How can i fetch the "subcategory name" as well as " items name". Please help me out.I have written some codes and tried to fetch but not working.
var json: NSArray!
do {
json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? NSArray
} catch {
print(error)
}
self.AllData = json.valueForKey("subcategory") as! Array<String>
print(self.AllData)
print(self.AllData.count)
But its not fetching any value
Other way also I have tried but still no data fetching . only the data is coming in json1.
do {
let json1 = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
// print(json1)
if let subcategory = json1["subcategory"] as? [[String: AnyObject]] {
for subname in subcategory {
if let name = subname["name"] as? String {
print(name)
}
if let items = subname["item"] as? [[String: AnyObject]] {
for item in items {
if let itemName = item["name"] as? String {
print(itemName)
}
}
}
}
}
} catch {
print(error)
}
At first its an array of objects/Dictionary.And you are creating an array of string. Thats why for subcategory it will not work.You need to create an array of Dictionaries like this:
do {
let json1 = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
self.AllData = json1.valueForKey("name") as! Array<String>
print(self.AllData)
print("Number of menu = \(json1.count)")
for var i in 0..<json1.count {
print(" \n \(i+1) row menu \n")
if let subs = json1[i]["subcategory"] as? [[String: AnyObject]] {
//print(subs)
for sub in subs {
if let name = sub["name"] as? String {
print("subcategory name= \t \(name)")
//print(name)
}
if let desc = sub["description"] as? String {
print("description= \t \(desc)")
// print(desc)
}
}
print("Number of subcategory= \(subs.count)")
for var i in 0..<subs.count {
if let items = subs[i]["item"] as? [[String: AnyObject]] {
print("items = ")
print(items.count)
for item in items {
if let itemName = item["name"] as? String {
print(itemName)
}
}
}
}
}
}
}catch {
print(error)
}
Try this one it will work accoording to your json data
This may just be a problem when cutting and pasting into the question, but it looks like your JSON data isn't formatted correctly (the []s and {}s don't match up). As the previous commentor said, you're dealing with an array of dictionaries not an array of strings. Try something like this:
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())
if let subs = json[0]["subcategory"] as? [[String: AnyObject]] {
for sub in subs {
if let name = sub["name"] as? String {
print(name)
}
if let items = sub["item"] as? [[String: AnyObject]] {
for item in items {
if let itemName = item["name"] as? String {
print(itemName)
}
}
}
}
}
} catch {
print(error)
}

Resources