How to search JSON element using SwiftyJSON in Swift 3 - ios

I search around here and little example to show how to search a json element in SwiftyJSON. I have below json structure, can anyone tech me? thanks.
var jsonData = {
"css":[
{
"path": "style.css",
"updated": "12432"
},
{
"path": "base.css",
"updated": "34627"
}
],
"html":[
{
"path": "home.htm",
"updated": "3223"
},
{
"path": "about",
"updated": "3987"
}
]
}
I want to search the "html" -> "home.htm" row. How to make use of filter method for it.
I got example like this for simple json structure, but in my case I have no idea.
{
countryid : "1"
name : "New York"
},
{
countryid : "2"
name : "Sydeny"
}
if let array = arrCountry.arrayObject as? [[String:String]],
foundItem = array.filter({ $0["name"] == "def"}).first {
print(foundItem)
}

let updated = json["html"].array?.filter { $0["path"].string == "home.htm" }.first?["updated"].string
print(updated)
// OR
for subJson in json["html"].arrayValue where subJson["path"].stringValue == "home.htm" {
let updated = subJson["updated"].stringValue
print(updated)
}

Related

Adding multiple children to Firebase database with Swift

I am trying to create multiple children inside a child. I can currently create this inside my recipe:
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
}
}
}
}
Using:
let recipe: [String : Any] = ["name" : self.recipe.name,
"ID" : self.recipe.key]
The class of the recipe looks like this:
class Recipe {
var name: String!
var key: String
init(from snapshot: FIRDataSnapshot) {
let snapshotValue = snapshot.value as! [String: Any]
self.name = snapshotValue["name"] as! String
self.key = snapshot.key
}
}
But I now want to create another array of children which would be inside "method" and look something like this.
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
"method": [
{
"step 1": "instruction 1"
},
{
"step 2": "instruction 2"
},
{
"step 3": "instruction 3"
}
]
}
}
}
}
Edit:
The recipe is updated this way
databaseRef.child("RecipeData").child("recipe").updateChildValues(recipe)
I have looked at Firebase How to update multiple children? which is written in javascript, but not sure how to implement it. Feel free to let me know if there are better questions or examples out there.
You can create multiple children inside of a node just as you have been doing with the "recipe" node. For example:
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
"method": {
"Step1":"instruction1",
"Step2":"instruction2",
"Step3":"instruction3"
}
}
}
}
This is better practice as you can look up each step by key. Although, as Firebase Database keys are strings ordered lexicographically, it would be better practice to use .childByAutoId() for each step, to ensure all the steps come in order and are unique. I'll just keep using "stepn" for this example though.
If you needed further information inside each step, just make one of the step keys a parent node again:
{
"RecipeData": {
"recipe": {
"-KjTSH4uPQ152Cr-hDok": {
"name": "Cook rice",
"ID": "-KjTSH4uPQ152Cr-hDok",
"method": {
"Step1": {
"SpatulaRequired" : true,
"Temp" : 400
}
}
}
}
}
This can be achieved by by calling .set() on a Dictionary of Dictionaries. For example:
let dict: [String:AnyObject] = ["Method":
["Step1":
["SpatulaRequired":true,
"temp":400],
["Ste‌​p2":
["SpatulaRequire‌​d":false,
"temp":500]‌​
]]
myDatabaseReference.set(dict)

Parse JSON with Swift JSON

How to get Value Radio Name With Swift JSON
I wrote like this
let response = JSON["topradio"]["Data"]
before this i created model for values but am not able to pic values like radio_name
{
"topradio": {
"result": "success",
"Data": [
[
{
"radio_name": "Kantipur",
"rimage": "radio/1422960479145155755920731096211441695162.jpeg",
"status": "1",
"user_faverate": "false",
"popular_radio": "0",
"radio_id": "4"
}
]
[
{
"radio_name": "Kantipur",
"rimage": "radio/1422960479145155755920731096211441695162.jpeg",
"status": "1",
"user_faverate": "false",
"popular_radio": "0",
"radio_id": "4"
}
]
]
}
Thanks in Advance
You can iterate through your nested data Array this way.
let dataArray = JSON["topradio"]["Data"].array
for item in dataArray {
let itemArray = item.array
for subItem in itemArray {
if let name = subItem["radio_name"].string {
print(name)
}
}
}

Get key of dictionary on JSON parse with SwiftyJSON

I want to get "key of dictionary" (that's what I called, not sure if it is right name) on this JSON
{
"People": {
"People with nice hair": {
"name": "Peter John",
"age": 12,
"books": [
{
"title": "Breaking Bad",
"release": "2011"
},
{
"title": "Twilight",
"release": "2012"
},
{
"title": "Gone Wild",
"release": "2013"
}
]
},
"People with jacket": {
"name": "Jason Bourne",
"age": 15,
"books": [
{
"title": "Breaking Bad",
"release": "2011"
},
{
"title": "Twilight",
"release": "2012"
},
{
"title": "Gone Wild",
"release": "2013"
}
]
}
}
}
First of all, I already created my People struct that will be used to map from those JSON.
Here is my people struct
struct People {
var peopleLooks:String?
var name:String?
var books = [Book]()
}
And here is my Book struct
struct Book {
var title:String?
var release:String?
}
From that JSON, I created engine with Alamofire and SwiftyJSON that will be called in my controller via completion handler
Alamofire.request(request).responseJSON { response in
if response.result.error == nil {
let json = JSON(response.result.value!)
success(json)
}
}
And here is what I do in my controller
Engine.instance.getPeople(request, success:(JSON?)->void),
success:{ (json) in
// getting all the json object
let jsonRecieve = JSON((json?.dictionaryObject)!)
// get list of people
let peoples = jsonRecieve["People"]
// from here, we try to map people into our struct that I don't know how.
}
My question is, how to map my peoples from jsonRecieve["People"] into my struct?
I want "People with nice hair" as a value of peopleLooks on my People struct. I thought "People with nice hair" is kind of key of dictionary or something, but I don't know how to get that.
Any help would be appreciated. Thank you!
While you iterate through dictionaries, for instance
for peeps in peoples
You can access key with
peeps.0
and value with
peeps.1
You can use key, value loop.
for (key,subJson):(String, JSON) in json["People"] {
// you can use key and subJson here.
}

Swift 3 looping JSON data

I'm attempting to loop through a JSON array sending data to a struct.
Here's my code that uses SwiftyJSON to return a JSON object:
performAPICall() {
json in
if(json != nil){
print("Here is the JSON:")
print(json["content"]["clients"])
let clients = json["content"]["clients"]
for client in clients {
var thisClient = Client()
thisClient.id = client["id"].string
thisClient.desc = client["desc"].string
thisClient.name = client["name"].string
self.clientArray.append(thisClient)
}
self.tableView.reloadData()
} else {
print("Something went very wrong..,")
}
}
I'm not quite sure why I'm getting "has no subscript" errors on the three strings.
Any help appreciated, thanks.
EDIT: Here's a sample of the JSON
{
"content": {
"clients": [{
"group": "client",
"id": "group_8oefXvIRV4",
"name": "John Doe",
"desc": "John's group."
}, {
"group": "client",
"id": "group_hVqIc1eEsZ",
"name": "Demo Client One",
"desc": "Demo Client One's description! "
}, {
"group": "client",
"id": "group_Yb0vvlscci",
"name": "Demo Client Two",
"desc": "This is Demo Client Two's group"
}]
}
}
You should use array method. Thus, your line
let clients = json["content"]["clients"]
should use array (and unwrap it safely):
guard let clients = json["content"]["clients"].array else {
print("didn't find content/clients")
return
}
// proceed with `for` loop here

Ruby use find to loop through an array and return the matching value

I am trying to loop through an array using find to find and return a specific id.
This is my structure:
{
"employees": [
{
"emp_id": "1",
"tutorials": [
{
"id": "test1"
},
{
"id": "test2"
},
{
"id": "test3"
},
{
"id": "test4"
},
{
"id": "test5"
}
]
}
]
}
So basically I am trying to see if the above structure contains a tutorial id of 'test3' and return it.(i.e return 'test3' in this case)
I can get the desired result using a combination of map and find like this:
my_tutorial = employees.map { |employee|
employee.tutorials.find { |tutorial|
tutorial.id == 'test3'
}
}.first
my_tutorial
But I want to know if there is a better way using find . I tried the following but it returns the ruby object instead of the id.
employees.find { |employee|
employee.tutorials.find { |tutorial|
tutorial.id == 'test3'
}
}
Here is what i did to make it work using find. Not sure if it is any better:
my_id = employees.find { |employee|
employee.tutorials.find { |tutorial|
tutorial.id == 'test3'
}
}
my_id.tutorials.first.id
If you have to get only the first record do as follows:
employees[0].tutorials.detect {|r| r.id == 'test3' }

Resources