RDowns RDowns - 24 days ago 10
JSON Question

How do I pluck this specific node out of from this JSON array?

I have an array being returned in

Xcode
which outputs the following:

["userDetails": {
id = 31;
"user_email" = "steve@gmail.com";
"user_name" = "Steve Downs";
}, "communities": <__NSArrayI 0x600000245f40>(
{
id = 5;
name = South;
},
{
id = 13;
name = HurraHarry;
},
{
id = 15;
name = EnclliffeT;
}
)
]


The code below correctly assigns the values contained within "communities" to their respective variables.

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

if let arr = json?["communities"] as? [[String:String]] {
self.communitiesArray = arr.flatMap { $0["name"]!}
self.communityIdsArray = arr.flatMap { $0["id"]!}
}

if let arr = json?["userDetails"] as? [AnyObject] {

self.playerId = (arr.flatMap { $0["id"]!} as (AnyObject)) as! [String]
print (self.playerId);
}


However I'm having trouble assigning
id
from
"userDetails"
. How do I take
id
from
"userDetails"
and assign it to self.playerId?

Answer

You can try something like this

if let dict = json?["userDetails"] as? [String:String] {
    self.playerId = dict["id"]
}
Comments