Hello i am new to swift and i am calling API through Alamofire and SwiftyJON and i am able to retrive response successfully but from that data i want to retrive only first two index of data let me explain you in brief
Here is my response
{
"previous_inspection_list" : [
{
"inspection_number" : "3",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "3",
"signature" : "img_ZbsOx3fx1r1555154350.png",
"status" : "1",
"fk_user_id" : "3",
"signature_name" : "Vishal Parmar",
"created_date" : "2019-04-13 05:19:10",
"updated_by" : "0",
"inspections_id" : "8",
"updated_date" : "0000-00-00 00:00:00"
},
{
"inspection_number" : "2",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "3",
"signature" : "img_uVQw3K4pfY1555140089.png",
"status" : "1",
"fk_user_id" : "3",
"signature_name" : "Vishal Parmar",
"created_date" : "2019-04-13 01:21:29",
"updated_by" : "0",
"inspections_id" : "6",
"updated_date" : "0000-00-00 00:00:00"
},
{
"inspection_number" : "1",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "2",
"signature" : "img_g6GrjsofPE1555137646.png",
"status" : "1",
"fk_user_id" : "2",
"signature_name" : "Mihir Panchasara",
"created_date" : "2019-04-13 00:40:46",
"updated_by" : "0",
"inspections_id" : "3",
"updated_date" : "0000-00-00 00:00:00"
}
],
"success" : "1",
"message" : "Successfully."
}
as you can able to see my response now i want to retrive only first two index value like below
Expected OutPut
for 1st index expected output
{
"inspection_number" : "3",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "3",
"signature" : "img_ZbsOx3fx1r1555154350.png",
"status" : "1",
"fk_user_id" : "3",
"signature_name" : "Vishal Parmar",
"created_date" : "2019-04-13 05:19:10",
"updated_by" : "0",
"inspections_id" : "8",
"updated_date" : "0000-00-00 00:00:00"
}
2nd Index Expected Output
{
"inspection_number" : "2",
"date_inspected" : "2019-04-13",
"fk_properties_id" : "2",
"created_by" : "3",
"signature" : "img_uVQw3K4pfY1555140089.png",
"status" : "1",
"fk_user_id" : "3",
"signature_name" : "Vishal Parmar",
"created_date" : "2019-04-13 01:21:29",
"updated_by" : "0",
"inspections_id" : "6",
"updated_date" : "0000-00-00 00:00:00"
}
let me show you my code which i have tried
let sampleArray = data.array
let firstdict = sampleArray![0]
print(firstdict)
let signature_name = firstdict["signature_name"].stringValue
let inspection_number = firstdict["inspection_number"].stringValue
let date_inspected = firstdict["date_inspected"].stringValue
let inspections_id = firstdict["inspections_id"].stringValue
self.lblFirstInspName.text = signature_name
self.lblInspNumber.text = "#\(inspection_number)"
self.lblFirstInspDate.text = date_inspected
self.inspID1 = inspections_id
let secondDict = sampleArray![1]
let signature_name1 = secondDict["signature_name"].stringValue
let inspection_number1 = secondDict["inspection_number"].stringValue
let date_inspected1 = secondDict["date_inspected"].stringValue
let inspections_id2 = secondDict["inspections_id"].stringValue
self.lblSeconfInspName.text = signature_name1
self.lblSecondInspNumber.text = "#\(inspection_number1)"
self.lblSecondInspDate.text = date_inspected1
self.inspID2 = inspections_id2
please see my code i am getting output as expected but when in response there is only one data then i am getting crash on second index because there is no data at second index
please someone help me
Add a safe check before fetching the second one
if let sampleArray = sampleArray, sampleArray.count > 1 {
let secondDict = sampleArray[1]
let signature_name1 = secondDict["signature_name"].stringValue
let inspection_number1 = secondDict["inspection_number"].stringValue
let date_inspected1 = secondDict["date_inspected"].stringValue
let inspections_id2 = secondDict["inspections_id"].stringValue
self.lblSeconfInspName.text = signature_name1
self.lblSecondInspNumber.text = "#\(inspection_number1)"
self.lblSecondInspDate.text = date_inspected1
self.inspID2 = inspections_id2
}
Try this function. I tried to put the important points inside the code.
func analysis() {
let rawData = data as! [String: Any] // Specify value type -> By doing this, you specify the type of value that is "JSON"
let arrayPreviousInspectionList = rawData["previous_inspection_list"] as! [[String: String]] // Getting "previous_inspection_list" and specifying its type -> it's list of [String: String]
if(arrayPreviousInspectionList.count >= 2) { // You must check the number of objects in the list
// first index
let firstInspection = arrayPreviousInspectionList[0]
let signature_name = firstInspection["signature_name"]!
let inspection_number = firstInspection["inspection_number"]!
let date_inspected = firstInspection["date_inspected"]!
let inspections_id = firstInspection["inspections_id"]!
self.lblFirstInspName.text = signature_name
self.lblInspNumber.text = "#\(inspection_number)"
self.lblFirstInspDate.text = date_inspected
self.inspID1 = inspections_id
// second index
let secondInspection = arrayPreviousInspectionList[1]
let signature_name1 = secondInspection["signature_name"]!
let inspection_number1 = secondInspection["inspection_number"]!
let date_inspected1 = secondInspection["date_inspected"]!
let inspections_id2 = secondInspection["inspections_id"]!
self.lblSeconfInspName.text = signature_name1
self.lblSecondInspNumber.text = "#\(inspection_number1)"
self.lblSecondInspDate.text = date_inspected1
self.inspID2 = inspections_id2
} else {
print("--- The number of inspections is less than 2")
}
}
Hope to be useful. Also sorry about my English.
Related
I'm trying to find a specific value in my JSON.
this my json
[
{
"airportName" : "Simon Mwansa Kapwepwe Intl",
"longitude" : 28.664999999999999,
"geometry" : {
"type" : "Point",
"coordinates" : [
28.664999999999999,
-12.994999999999999
]
},
"countryCode" : "ZMB",
"countryName" : "Zambia",
"latitude" : -12.994999999999999,
"cityName" : "Ndola",
"airportCode" : "FLSK"
},
{
"airportName" : "Mafikeng",
"longitude" : 25.544469444444445,
"geometry" : {
"type" : "Point",
"coordinates" : [
25.544469444444445,
-25.807447222222223
]
},
"countryCode" : "ZAF",
"countryName" : "South African Rep",
"latitude" : -25.807447222222223,
"cityName" : "Mafikeng",
"airportCode" : "FAMM"
}]
now if I write this code it works!
for item in 0...json.count {
i = i+1
if json[i]["airportName"] == "Simon Mwansa Kapwepwe Intl" {
print ("I found it")
}
if I try to pass the parameter to search with a function it doesn't work, swift give me a error say :Binary operator '==' cannot be applied to operands of type 'JSON' and 'String'
func cerca (nomeApt: String){
var i = 0
for item in 0...json.count {
i = i+1
if json[i]["airportName"] == nomeApt { // error I don't know
print ("I found it")
}
}
}
Honestly, I don't know why? any idea how to solve the issue? thanks a lot
You can try to use decodable,
And that will give you a simple array where you can loop and access the properties.
import Foundation
let json = """
[
{
"airportName" : "Simon Mwansa Kapwepwe Intl",
"longitude" : 28.664999999999999,
"geometry" : {
"type" : "Point",
"coordinates" : [
28.664999999999999,
-12.994999999999999
]
},
"countryCode" : "ZMB",
"countryName" : "Zambia",
"latitude" : -12.994999999999999,
"cityName" : "Ndola",
"airportCode" : "FLSK"
},
{
"airportName" : "Mafikeng",
"longitude" : 25.544469444444445,
"geometry" : {
"type" : "Point",
"coordinates" : [
25.544469444444445,
-25.807447222222223
]
},
"countryCode" : "ZAF",
"countryName" : "South African Rep",
"latitude" : -25.807447222222223,
"cityName" : "Mafikeng",
"airportCode" : "FAMM"
}
]
""".data(using: .utf8)!
struct Geometry: Decodable {
var type: String
var coordinates: [Double]
}
struct Airports: Decodable {
var airportName : String
var longitude : Double
var geometry: Geometry
var countryCode : String
var countryName: String
var latitude: Double
var cityName: String
var airportCode :String
}
func findSpecifAirport(airportName: String) -> Bool {
if let myStruct = try? JSONDecoder().decode([JsonDecoder].self, from: json) {
let foundSpecific = myStruct.filter { $0.airportName == airportName }
return !foundSpecific.isEmpty;
}
return false
}
you could use it like this
let hasFoundIt = findSpecifAirport(airportName: "Simon Mwansa Kapwepwe Intl")
Convert json to string, change the line to:
if json[i]["airportName"] as? String == nomeApt {
I have three arrays that correlate to one another (Users, Wins, and Lost), Wins[0] through Wins[2] stand for Users[0] through Users[2]. If Users[0] through Users[2] won and Users[3] as well as Users[4] lost, then Lost[3] and Lost[4] need to be equal to 1.
var Users = ["user1", "user2", "user3", "user4", "user5"];
var Wins = ["1", "1", "1", "0", "0"];
var Lost = ["0", "0", "0", "0", "0"]; //Lost[3] and Lost[4] need to be equal to 1
You can simply use map and a ternary operator to produce the Lost array:
var Users = ["user1", "user2", "user3", "user4", "user5"];
var Wins = ["1", "1", "1", "0", "0"];
var Lost = Wins.map((win) => win === "1" ? "0" : "1");
console.log(Lost);
const lost = wins.map(w => w === "1" ? "0" : "1");
I am having trouble figuring out how to map this JSON correctly in React Native. Do I need to rewrite this json?
This is the json
"rewards" : {
"0" : {
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
},
"1" : {
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
},
{...}
Here is what I tried for mapping
renderItems(){
const{rewards} = this.props;
return rewards.map((data, i) => {
return (<Text> {data[i].name} </Text>)
})
}
Yes, you’ll need to rewrite the JSON because map() is expecting rewards to be an array of objects. For example:
{
"rewards": [{
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
},
{
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
}]
}
You’ll also want to use JSON.parse on the rewards prop if you’re not already. Here is an example of how you might use JSON.parse when rendering the component with the rewards prop:
render() {
const rewardsJSON = '{"rewards":[{"entries":0,"image":"url","name":"PlayStation 4 Pro 1TB Console","url":"","price":399.99},{"entries":0,"image":"url","name":"Xbox One S 500GB","url":"","price":249.99}]}';
return (
<YOUR_COMPONENT
rewards=JSON.parse(rewardsJSON).rewards
/>
);
}
.map() should be called on an array. rewards is not an array here, so a solution would be to convert it to an array first.
Suppose your json is this:
const myJson =
{
"rewards" : {
"0" : {
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
},
"1" : {
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
}
}
You can dynamically convert it (with any length) to an array:
let index = 0
let dataArr = []
while (myJson.rewards[index]) {
arr.push(myJson.rewards[index])
index++
}
hopping the above code is clear enough...
So now the dataArr contains your data like:
dataArr = [{
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
},
{
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
}]
And finally it's the time to map it as you want:
return dataArr.map((data, i) => (<Text key={i}> {data.name} </Text>))
I'm trying to make three arrays based on the JSON Data that I'm pulling from my restaurant. I want to have an array of Entre, Main, & Dessert that will display in a tableView Object. This is the code I'm using to pull in data:
func loadMeals() {
Helpers.showActivityIndicator(activityIndicator, view)
if let restaurantId = restaurant?.id {
APIManager.shared.getMeals(restaurantId: restaurantId, completionHandler: { (json) in
if json != nil {
self.meals = []
if let tempMeals = json["meals"].array {
for item in tempMeals {
let meal = Meal(json: item)
self.meals.append(meal)
}
self.tableView.reloadData()
Helpers.hideActivityIndicator(self.activityIndicator)
}
}
})
}
}
Item prints out:
items {
"name" : "Spinach Artichoke",
"course" : "entres",
"short_description" : "savory",
"id" : 20,
"image" : "http:\/\/localhost:8000\/media\/product_images\/artichoke.jpg",
"usage" : "homestyle",
"sizes" : [
{
"size" : 3,
"id" : 24,
"product_id" : 20,
"price" : 55.899999999999999
},
{
"size" : 4,
"id" : 25,
"product_id" : 20,
"price" : 78
},
{
"size" : 5,
"id" : 26,
"product_id" : 20,
"price" : 125
}
]
}
items {
"name" : "Pizza",
"course" : "main",
"short_description" : "Melty cheese",
"id" : 19,
"image" : "http:\/\/localhost:8000\/media\/product_images\/pizza.jpg",
"usage" : "top",
"sizes" : [
{
"size" : 6,
"id" : 23,
"product_id" : 19,
"price" : 75.989999999999995
}
]
}
items {
"name" : "Chocolate Mousee Devil's cake",
"course" : "dessert",
"short_description" : "Sweet And Smooth",
"id" : 18,
"image" : "http:\/\/localhost:8000\/media\/product_images\/Devils_cake.jpg",
"usage" : "sweets",
"sizes" : [
{
"size" : 2,
"id" : 20,
"product_id" : 18,
"price" : 50
},
{
"size" : 3,
"id" : 21,
"product_id" : 18,
"price" : 120
},
{
"size" : 4,
"id" : 22,
"product_id" : 18,
"price" : 376
}
]
}
I'm trying to figure out how to create the arrays by pulling the data from this function. Any help would be appreciated.
Just You need to group By course
meals Array will be [[String:Any]] Key will be course Any will be Array of course items
func loadMeals() {
Helpers.showActivityIndicator(activityIndicator, view)
if let restaurantId = restaurant?.id {
APIManager.shared.getMeals(restaurantId: restaurantId, completionHandler: { (json) in
if json != nil {
self.meals = []
if let tempMeals = json["meals"].array {
self.meals = Dictionary(grouping: tempMeals, by: { $0["course"] as! String })
self.tableView.reloadData()
Helpers.hideActivityIndicator(self.activityIndicator)
}
}
})
}
}
OutPut Console:
["Main": [["name": Chocolate Mousee Devil's cake, "course": Main, "short_description": Sweet And Smooth, "id": 18, "image": http://localhost:8000/media/product_images/Devils_cake.jpg, "usage": sweets, "sizes": <__NSArrayI 0x60c0002456a0>(
{
id = 20;
price = 50;
"product_id" = 18;
size = 2;
},
{
id = 21;
price = 120;
"product_id" = 18;
size = 3;
},
{
id = 22;
price = 376;
"product_id" = 18;
size = 4;
}
)
]], "dessert": [["name": Chocolate Mousee Devil's cake, "course": dessert, "short_description": Sweet And Smooth, "id": 18, "image": http://localhost:8000/media/product_images/Devils_cake.jpg, "usage": sweets, "sizes": <__NSArrayI 0x60c000243d50>(
{
id = 20;
price = 50;
"product_id" = 18;
size = 2;
},
{
id = 21;
price = 120;
"product_id" = 18;
size = 3;
},
{
id = 22;
price = 376;
"product_id" = 18;
size = 4;
}
)
], ["name": Chocolate Mousee Devil's cake, "course": dessert, "short_description": Sweet And Smooth, "id": 18, "image": http://localhost:8000/media/product_images/Devils_cake.jpg, "usage": sweets, "sizes": <__NSArrayI 0x60c000248910>(
{
id = 20;
price = 50;
"product_id" = 18;
size = 2;
},
{
id = 21;
price = 120;
"product_id" = 18;
size = 3;
},
{
id = 22;
price = 376;
"product_id" = 18;
size = 4;
}
)
]]]
I have the following schema, blog collection & friendscoll as below
blogpostcollection
{
"_id" : ObjectId("4fff0bf18bf0d19c4f1a5826"),
"author" : "joe",
"text" : "Here is the text...",
"userid" : 0
}
{
"_id" : ObjectId("4fff0bf18bf0d19c4f1a5827"),
"author" : "blake",
"text" : "Here is the text...",
"userid" : 1
}
{
"_id" : ObjectId("4fff0bf18bf0d19c4f1a5828"),
"author" : "joe",
"text" : "Here is the text...",
"userid" : 2
}
myfriendscoll
{
"myid": 999,
"data": [
{
"uid": 1,
"name": "Raul"
},
{
"uid": 3,
"name": "John K"
} ]
}
I want to find all documents in blogpostcollection, where the userid exists as uid, in the myfriendscoll collection.
So in effect, something like..
var user = db.myfriendscoll.findOne({"myid" : 999}, {"data.uid": 1});
db.blogpostcollection.find( {"userid" : {$in : user.data.uid}});
This doesn't work, but is there a way to get it to work?...Thanks!
If you are using development version 2.1 or when you move to 2.2 once it's released you can use the aggregation framework to get the format you want back from the first query:
var ret=db.myfriendscoll.aggregate([
{$match:{"myid" : 999}},
{$project:{_id:0,uid:"$data.uid"}}
]);
var uids=ret.result[0].uid;
db.blogpostcollection.find({userid:{$in:uids}})
You'll need to extract the actual uid values into an array to use with $in. Try this:
var user = db.myfriendscoll.findOne({"myid" : 999}, {"data.uid": 1});
var uids = user.data.map(function(v){ return v.uid });
db.blogpostcollection.find( {"userid" : {$in : uids}});