How to index into Array of Dictionaries - ios

I have an object that looks like this in the console. It seems like an array with a dictionary inside. How can I get to the address field?
Optional((
{
address = "xxxxxxx#gmail.com";
verified = 1;
}
))
The object comes from this object:
<METDocument key: <collection: users, ID: KTsCySacEAiz3eDnf>, fields: {
emails = (
{
address = "xxxxxxx#gmail.com";
verified = 1;
}
);
profile = {
address = {
city = Oslo;
country = nor;
lineOne = "address";
lineTwo = "";
zip = 0264;
};
birthdate = "1985-09-01 23:00:00 +0000";
card = {
last4 = 4242;
verified = 1;
};
filledOut = 1;
gender = Male;
name = {
first = "Elon";
last = "Musk";
};
phone = 911;
validated = 1;
};
}>
I access the emails key by this method:
let emails = users.allDocuments[0].valueForKey("emails")

The content of the object is an optional array.
There are two options:
Safe access:
if let emails = users.allDocuments[0].objectForKey("emails") where emails.count > 0 {
if let address = emails[0]["address"] as? String {
print(address)
}
}
If it's guaranteed that the dictionary in the array and the key address exists:
let emails = users.allDocuments[0].objectForKey("emails")!
let address = emails[0]["address"] as! String

Related

JSON: Extracting Data Using Alamofire and Swift 3

Can anyone tell me how to get the data out of this JSON?
Here is my code followed by the JSON
let URL = "URL"
Alamofire.request(URL).responseJSON
{ response in
print("HereBegins: = \(response)")
let result = response.result.value as? [String:Any]
}
the json being returned is...
HereBegins: = SUCCESS:
{
items =
(
{
addToCartUrl = "blah blah URL";
affiliateAddToCartUrl = "blah blah another URL";
availableOnline = 0;
brandName = Generic;
bundle = 0;
categoryNode = "976759_1071964_976788";
categoryPath = "Food/Fresh Food/Dairy, Eggs & Cheese/Milk & Cream";
clearance = 0;
customerRating = "5.0";
customerRatingImage = "http://i2.walmartimages.com/i/CustRating/5.gif";
freeShipToStore = 0;
freeShippingOver50Dollars = 1;
giftOptions = {
allowGiftMessage = 0;
allowGiftReceipt = 0;
allowGiftWrap = 0;
};
imageEntities =
(
{
entityType = SECONDARY;
largeImage = "https://i5.walmartimages.com/asr/c2bc3886-fb4f-4c46-b7e9-0cc4ebabc7c1_1.d42acf75b29b132532d5953b139b115f.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF";
mediumImage = "https://i5.walmartimages.com/asr/c2bc3886-fb4f-4c46-b7e9-0cc4ebabc7c1_1.d42acf75b29b132532d5953b139b115f.jpeg?odnHeight=180&odnWidth=180&odnBg=FFFFFF";
thumbnailImage = "https://i5.walmartimages.com/asr/c2bc3886-fb4f-4c46-b7e9-0cc4ebabc7c1_1.d42acf75b29b132532d5953b139b115f.jpeg?odnHeight=100&odnWidth=100&odnBg=FFFFFF";
},
{
entityType = PRIMARY;
largeImage = "https://i5.walmartimages.com/asr/1d575fe6-b8c9-4dc6-821b-42cbde621373_1.4764431b7ebfb4707c0a2f7fe47e85cc.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF";
mediumImage = "https://i5.walmartimages.com/asr/1d575fe6-b8c9-4dc6-821b-42cbde621373_1.4764431b7ebfb4707c0a2f7fe47e85cc.jpeg?odnHeight=180&odnWidth=180&odnBg=FFFFFF";
thumbnailImage = "https://i5.walmartimages.com/asr/1d575fe6-b8c9-4dc6-821b-42cbde621373_1.4764431b7ebfb4707c0a2f7fe47e85cc.jpeg?odnHeight=100&odnWidth=100&odnBg=FFFFFF";
}
);
isTwoDayShippingEligible = 0;
itemId = 46491746;
largeImage = "https://i5.walmartimages.com/asr/1d575fe6-b8c9-4dc6-821b-42cbde621373_1.4764431b7ebfb4707c0a2f7fe47e85cc.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF";
longDescription = "<br><b>Great Value Vanilla Almond Milk, 64 fl oz:</b><br><ul><li>Delicious flavor</li><li>Great Value almond milk comes in a 64 fl oz carton</li><li>Vitamins A, D and E added</li><li>Added calcium</li><li>Only 80 calories per serving</li></ul>";
marketplace = 0;
mediumImage = "https://i5.walmartimages.com/asr/1d575fe6-b8c9-4dc6-821b-42cbde621373_1.4764431b7ebfb4707c0a2f7fe47e85cc.jpeg?odnHeight=180&odnWidth=180&odnBg=FFFFFF";
modelNumber = 11951;
name = "Great Value Vanilla Almond Milk, 64 fl oz";
ninetySevenCentShipping = 0;
numReviews = 3;
offerType = "STORE_ONLY";
parentItemId = 46491746;
preOrder = 0;
productTrackingUrl = "http://linksynergy.walmart.com/fs-bin/click?id=|LSNID|&offerid=223073.7200&type=14&catid=8&subid=0&hid=7200&tmpid=1082&RD_PARM1=https%253A%252F%252Fwww.walmart.com%252Fip%252FGreat-Value-Vanilla-Almond-Milk-64-fl-oz%252F46491746%253Faffp1%253DHzNQqMKL6fuAwFZnu_RUqysY3U3RzuxH0bQKAHNYr0Q%2526affilsrc%253Dapi";
productUrl = "http://c.affil.walmart.com/t/api03?l=https%3A%2F%2Fwww.walmart.com%2Fip%2FGreat-Value-Vanilla-Almond-Milk-64-fl-oz%2F46491746%3Faffp1%3DHzNQqMKL6fuAwFZnu_RUqysY3U3RzuxH0bQKAHNYr0Q%26affilsrc%3Dapi%26veh%3Daff%26wmlspartner%3Dreadonlyapi";
salePrice = "2.58";
shipToStore = 0;
standardShipRate = 0;
stock = "Not available";
thumbnailImage = "https://i5.walmartimages.com/asr/1d575fe6-b8c9-4dc6-821b-42cbde621373_1.4764431b7ebfb4707c0a2f7fe47e85cc.jpeg?odnHeight=100&odnWidth=100&odnBg=FFFFFF";
upc = 078742052366;
}
);
}
Figured it out.
if let resData = result["items"].arrayObject {
arrRes = resData as! [[String:AnyObject]]
for element in arrRes[0]
{
print(element)
}
print(arrRes[0]["name"])

How to search an element in Array of Dictionary?

Below mentioned is my array. I need to check if the barcode 8901058847857 or barcode xxxxxxxxxxx exists in array or not.
(
{
barcode = 8901058847857;
image = (
);
name = "Maggi Hot Heads";
productTotal = "60.00";
quantity = 3;
},
{
barcode = 8901491101837;
image = (
);
name = "Lays Classic Salted";
productTotal = "20.00";
quantity = 1;
}
)
I tried using array.contains or array.elements but it is not working because barcode exists in an array.
** Try this **
// Put your key in predicate that is "barcode"
var namePredicate = NSPredicate(format: "barcode contains[c] %#",searchString);
let filteredArray = arrayOfDict.filter { namePredicate.evaluate(with: $0) };
print("names = ,\(filteredArray)")
You can search your array of dictionaries using contains where but you need to cast your value from Any to Int before trying to compare them:
if array.contains(where: {$0["barcode"] as? Int ?? 0 == 8901058847857}) {
print(true)
}
You can also run for loop to check the presence of element in your Array of dictionary.
let DictnaryArray = (
{
barcode = 8901058847857;
image = (
);
name = "Maggi Hot Heads";
productTotal = "60.00";
quantity = 3;
},
{
barcode = 8901491101837;
image = (
);
name = "Lays Classic Salted";
productTotal = "20.00";
quantity = 1;
}
)
for (index,element) in DictnaryArray{
let dict = DictnaryArray[index]
if dict["barcode"] == 8901058847857 || dict["barcode"] == XXXXXXXXXXX{
print("BarCode Exist")
print("\(dict["barcode"])")
}
}
Hope it helps!

How Parse JSON from API [duplicate]

This question already has answers here:
type 'Any' has no subscript members
(2 answers)
Closed 5 years ago.
i know to much ask like this. i already searching but not match with my problems.
oke i will try explain with my code
i have data API Like this
["profile": {
accountId = 58e470a0c50472851060d083;
androidDeviceId = "[\"3453247ddcf3f809\"]";
androidVersion = 21;
appId = (
"c46b4c10-62ce-11e6-bdd4-59e4df4b8410",
"fac915f0-fe2b-11e6-9dfb-55339bd7be35"
);
appVersion = "v5.1.0";
avatar = "https://account.8villages.com/uploads/images/5/1491366164_bnx1t0rudi.jpg";
birthDate = "12/03/1994";
"channel-group" = android;
communityId = 553e09b251906884443eff85;
coordinates = {
coordinates = (
"106.9602383333333",
"-6.249333333333334"
);
type = Point;
};
crop = "";
crops = "<null>";
customerId = 5369bd85cae84d0e03246a7c;
dateSubmitted = {
iso = "2017-04-05T04:20:48.483Z";
timestamp = 1491366048;
};
fullName = "Megi Fernanda";
gender = "Laki-laki";
homeAddress = Payakumbuah;
location = "Kota Payakumbuh";
moderation = {
at = {
iso = "2017-04-05T04:20:48.483Z";
timestamp = 1491366048;
};
by = auto;
status = moderated;
};
skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations = {
articles = 0;
forums = 0;
questions = 2;
responses = 0;
storeItems = 1;
};
type = users;
university = "Politeknik Negeri Pertanian Payakumbuh";
}, "accessToken": {
key = "lH5aYvnp2JAZ6zoKQK4mpfsxCI0.";
secret = "yfZfTZbsaVIhKCbksGHQnPcPg9mKtoRAKyvjg_cgMeo.";
}]
i already can got fullName, Addres, Skill State etc
if let profile = json["profile"] as? NSDictionary {
let name = profile["fullName"]
let alamat = profile["Skill"]
}
but i don't know how to get atribut in totalConversation like question, storeItems, points
skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations = {
articles = 0;
forums = 0;
questions = 2;
responses = 0;
storeItems = 1;
};
i tried like
let profile = json["profile"]["totalConversation"] as? NSDictionary
error sign : Type 'any?' has no subscript members
You got that error because json["profile"] is Any type and it doesn't have any subscript. So you need to cast json["profile"] to a dictionary, [String: Any] is dictionary type in Swift.
if let profile = json["profile"] as? [String: Any] {
if let totalConversations = profile["totalConversations"] as? [String: Any] {
let questions = totalConversations["questions"] as? Int
}
}

Indexing into NSArray with JSON object

I receive an object that is sent as a pointer to a collection.
I can access the fields directly as an NSDictionary.
The emails field is sent as an array, and I receive it in parentheses. Currently I get the emailaddress by what I feel is a roundabout method.
How can I most efficiently get to the email address?
let allDoc = users.allDocuments[0]
print("allDoc: \(allDoc)")
let emailsArray = users.allDocuments[0].valueForKey("emails") as! NSArray
print("emailsArray: \(emailsArray)")
let emailAddress = emailsArray[0]["address"] as! String
print("emailAddress: \(emailAddress)")
Console output:
allDoc: <METDocument key: <collection: users, ID: kzzw3vcqukD62xEyz>, fields: {
emails = (
{
address = "xxxx#gmail.com";
verified = 1;
}
);
profile = {
address = {
city = "";
country = nor;
lineOne = "";
lineTwo = "";
zip = "";
};
card = {
last4 = 4242;
verified = 1;
};
filledOut = 1;
name = {
first = XXXX;
last = XXXX;
};
phone = 9999999999;
validated = 1;
};
}>
emailsArray: (
{
address = "xxxx#gmail.com";
verified = 1;
}
)
emailAddress: xxxx#gmail.com
If you just want the email address you could simply do:
let emailsAddress = users.allDocuments[0]["emails"][0][#"address"] as! String
print("emailAddress: \(emailAddress)")
But it really is better to use multiple lines. It makes the code much easier to read and debug. Also, putting all that onto one line doesn't allow any error checking. What if the #"emails" key has an empty array, for example? The code will crash.

Parse Json using SwiftyJson

I am able to get the entire JSon array parsed. It outputs to console with no issue. I can't seem to get the individual params from the array... my json looks like:
[{
City = NYC;
Device = "<null>";
DisplayAs = "Steve Hutson";
FirstName = Steve;
LastName = Hutson;
MobilePhone = "000-000-0000";
Org = "<null>";
Region = "";
Role = INSPECTOR;
SupervisorID = "73990";
email = "email#email.com";
fLast = shutson;
"gz_modtimestamp" = "2015-07-28 14:42:41";
id = 96;
isActive = YES;
lastupdated = "<null>";
sendemail = 1;
token = "<null>";
userpassword = "xxx";
},{
City = DET;
Device = "<null>";
DisplayAs = "Filipe Washington";
FirstName = Filipe;
LastName = Washington;
MobilePhone = "000-000-0000";
Org = "<null>";
Region = "";
Role = INSPECTOR;
SupervisorID = "6567";
email = "email#email.com";
fLast = shutson;
"gz_modtimestamp" = "2015-07-28 13:02:09";
id = 93;
isActive = YES;
lastupdated = "<null>";
sendemail = 1;
token = "<null>";
userpassword = "xxx";
}]
In my main ViewController.swift file my json request looks like:
var myData:NSData = getJSON("http://xxxx/getusersData.php")
var myDict:NSArray = parseJSON(myData)
println(myDict)
This prints my entire json object which is perfect. However my issue is, how do I get only the FirstName's in an array? By index this works:
println(myDict[0]["FirstName"]) how ever, it only brings back one item.
I am trying to insert specific json items into sqlite which i am using SQLite.swift but i need to know how to retrieve specific item parameters as I would if i was using AJAX.
I am trying to retrieve FirstName, Email and UserPassword info.
Any help would be appreciated.
You can iterate over the JSON object and retrieve that info:
for (index: String, subJson: JSON) in json {
//Do something you want
var firstName = subJson["FirstName"].stringValue
var email = subJson["email"].stringValue
var userPassword = subJson["userpassword"].stringValue
// Build the sqlite query with the variables here
}
As a clarification, you don't access the values directly as in json["FirstName"], you must also use the type functions from SwiftyJSON. In your case they're both strings, so stringValue is used. If you needed and int, it'd be intValue.
There's also the option of just json["FirstName"].string in case the field is optional. Take a look at the readme

Resources