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)!
Related
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"
} ] }
In my angular app, I get the values from service as an array of objects like below.
temp= [
{
"a": "AAA",
"b": "bbbb",
"c": "CCCC",
"d": "ddddd",
},
{
"a": "lmn",
"b": "opq",
"c": "rst",
"d": "uvw",
}
]
I need to format this temp to array of array of strings:
newTemp =
[
['AAA', 'bbbb', 'CCCC', 'ddddd'],
['lmn', 'opq', 'rst', 'uvw'],
];
Should we need to do a forloop on each object or is there any straight forward way.
You can use Array.map
let newArray = arr.map(a => Object.values(a))
If you cant use Object.values
let newArray = arr.map(a => Object.keys(a).map(k => a[k]))
Output
(2) [Array(4), Array(4)]
0:(4) ["AAA", "bbbb", "CCCC", "ddddd"]
1:(4) ["lmn", "opq", "rst", "uvw"]
Try the following :
temp= [
{
"a": "AAA",
"b": "bbbb",
"c": "CCCC",
"d": "ddddd",
},
{
"a": "lmn",
"b": "opq",
"c": "rst",
"d": "uvw",
}
]
var newTemp = [];
temp.forEach(function(obj){
var arr = [];
Object.keys(obj).forEach(function(key){
arr.push(obj[key]);
})
newTemp.push(arr);
});
console.log(newTemp);
I have a dictionary which I want to append some items.
**This is my dictionary which I want to achieve: **
let parameters: [String: Any] = [
{
"ResultsList": [{
"UserId": "b806e283-066f-4081-aafe-1fe216a57c35",
"FriendUserId": "7a2ec150-cdb3-4600-84f8-2dab970bfa0c",
"TransferDate": "2017-11-23",
"UserAnswers": [{
"AnswerId": "b7562603-614d-11e7-a7e0-484d7ee0cd26",
"LastAnsweredDate": "2017-11-23",
"QuestionId": "0b60f35e-5d80-11e7-a7e0-484d7ee0cd26"
},
{
"AnswerId": "b7562603-614d-11e7-a7e0-484d7ee0cd26",
"LastAnsweredDate": "2017-11-23",
"QuestionId": "0b60f35e-5d80-11e7-a7e0-484d7ee0cd26"
}
]
}]
}
]
And this is my current dictionary which I want to make the loop and add the items.
let parameters: [String: Any] = [
{
ResultsList: [
{
UserId: “b806e283-066f-4081-aafe-1fe216a57c35”
FriendUserId: “7a2ec150-cdb3-4600-84f8-2dab970bfa0c”
TransferDate: “2017-11-23”
UserAnswers: [
{
AnswerId: “b7562603-614d-11e7-a7e0-484d7ee0cd26"
LastAnsweredDate: “2017-11-23”
QuestionId : “0b60f35e-5d80-11e7-a7e0-484d7ee0cd26"
}
]
}
]
}
]
I have 3 arrays which I want to loop through and append to the dictionary
var AnswerId = [ “b7562603-614d-11e7-a7e0-484d7ee0cd26", “aasdaas-614d-11e7-a7e0-484d7ee0cd26", “b756asd03-614d-11e7-a7e0-484d7ee0cd26"]
var LastAnsweredDate = [“2017-11-23”, “2017-11-23”, “2017-11-22”]
var QuestionId = [“0b60f35e-5d80-11e7-a7e0-484d7ee0cd26",“asdasd-5d80-11e7-a7e0-484d7ee0cd26",“asdasd-5d80-11e7-a7e0-484d7ee0cd26"]
Can someone please help to achieve this result?
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)
}
}
I'm using SwiftyJSON to create a data dictionary in JSON.
Now I want to arrange one of the sub dictionaries called fb_friends by friend_health_points.
I tried using Sort or any other manipulation but I get String/JSON errors.
So basically I'm trying to sort it so that 150 health points will be first and 20 will be last in that data dictionary.
This is the data:
var data: JSON = [
"user_id": 7742,
"name": "Bla",
"fb_friends": [
[
"friend_id": 202072,
"friend_name": "Bla Bla",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 50,
],
[
"friend_id": 502333,
"friend_name": "hdfghdfghfdgh",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 150,
],
[
"friend_id": 202072,
"friend_name": "gjhkghjk",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 20,
]
]
This is a solution without third-party libraries
var data = [
"user_id": 7742,
"name": "Bla",
"fb_friends": [
[
"friend_id": 202072,
"friend_name": "Bla Bla",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 50,
],
[
"friend_id": 502333,
"friend_name": "hdfghdfghfdgh",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 150,
],
[
"friend_id": 202072,
"friend_name": "gjhkghjk",
"friend_photo_url": "https://www.gravatar.com/avatar/",
"friend_health_points": 20,
]
]
]
let friends = (data["fb_friends"] as! [[String:AnyObject]]).sort{ ($0["friend_health_points"] as! Int) > $1["friend_health_points"] as! Int}
data["fb_friends"] = friends
print(data)
let json = JSON(data)
Ok I found the answer, because the object is of type SwiftyJSON I can use arrayValue to extract it to array.
So this will give me back a sorted array of friends.
let fbFriends = data["fb_friends"]
let friendsArray = fbFriends.arrayValue
let sortedFriends = friendsArray.sort { $0["friend_health_points"].doubleValue > $1["friend_health_points"].doubleValue }