SwiftyJSON array empty - ios

I want to retrieve data from a JSON file with SwiftyJSON and Alamofire. This is the JSON data:
json: {
"data" : {
"monitors" : [
{
"lines" : [
{
"towards" : "LEOPOLDAU",
"realtimeSupported" : true,
"departures" : {
"departure" : [
{
"departureTime" : {
"countdown" : 2,
"timePlanned" : "2015-09-09T18:47:03.000+0200",
"timeReal" : "2015-09-09T18:47:03.000+0200"
}
},
{
"departureTime" : {
"countdown" : 6,
"timePlanned" : "2015-09-09T18:51:03.000+0200",
"timeReal" : "2015-09-09T18:51:03.000+0200"
}
}
]
},
"lineId" : 301,
"platform" : "1",
"trafficjam" : false,
"richtungsId" : "1",
"direction" : "H",
"type" : "ptMetro",
"name" : "U1",
"barrierFree" : true
}
],
"attributes" : {
},
"locationStop" : {
"type" : "Feature",
"geometry" : {
"type" : "Point",
"coordinates" : [
16.4330680046932,
48.2430825589716
]
},
"properties" : {
"municipality" : "Wien",
"title" : "Kagran",
"coordName" : "WGS84",
"municipalityId" : 90000,
"type" : "stop",
"gate" : "1",
"name" : "60200627",
"attributes" : {
"rbl" : 4127
}
}
}
}
]
}
,
"message" : {
"value" : "OK",
"serverTime" : "2015-09-09T18:45:08.998+0200",
"messageCode" : 1
}
}
What I want to do now is get the data of lines into an array. I tried several combinations for that, e.g.
let departureArray = jsonData["data"]["monitors"][0]["lines"][0].array
or
let departureArray = jsonData["data"]["monitors"]["lines"].array
but my array is always empty. Does anyone has an idea how to do this properly?

Your expected array departureArray is in fact a dictionary
let departureDictionary = jsonData["data"]["monitors"][0]["lines"][0].dictionary

Related

Get multiple strings from JSON

So the JSON variable let json = JSON(nearbyChargingSites.jsonString!) contains the current data.:
{
"timestamp" : 1626902257093,
"superchargers" : [
{
"location" : {
"lat" : 63.325319,
"long" : 10.305137
},
"total_stalls" : 19,
"distance_miles" : 10.064082000000001,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 15,
"name" : "Leinstrand, Norway - Klett"
},
{
"location" : {
"lat" : 63.466445999999998,
"long" : 10.91766
},
"total_stalls" : 16,
"distance_miles" : 11.838984999999999,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 16,
"name" : "Stjørdal, Norway"
},
{
"location" : {
"lat" : 63.734355000000001,
"long" : 11.281487
},
"total_stalls" : 12,
"distance_miles" : 31.206503999999999,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 11,
"name" : "Levanger, Norway"
},
{
"location" : {
"lat" : 62.832030000000003,
"long" : 10.009639999999999
},
"total_stalls" : 20,
"distance_miles" : 44.117753,
"type" : "supercharger",
"site_closed" : false,
"available_stalls" : 17,
"name" : "Berkåk, Norway"
}
],
"congestion_sync_time_utc_secs" : 1626902199,
"destination_charging" : [
{
"distance_miles" : 23.366278999999999,
"name" : "Bårdshaug Herregård",
"location" : {
"lat" : 63.299208,
"long" : 9.8448650000000004
},
"type" : "destination"
},
{
"distance_miles" : 38.390034,
"name" : "Fosen Fjordhotel",
"location" : {
"lat" : 63.959356999999997,
"long" : 10.223908
},
"type" : "destination"
},
{
"distance_miles" : 46.220022999999998,
"name" : "Falksenteret",
"location" : {
"lat" : 63.293301999999997,
"long" : 9.0834460000000004
},
"type" : "destination"
},
{
"distance_miles" : 54.981445000000001,
"name" : "Væktarstua",
"location" : {
"lat" : 62.908683000000003,
"long" : 11.893306000000001
},
"type" : "destination"
}
]
}
I use SwiftyJSON and tries to get the superchargers latitude, longitude and name, like this:
let jsonName = json["superchargers"]["name"]
let jsonLat = json["superchargers"]["location"]["lat"]
let jsonLong = json["superchargers"]["location"]["long"]
When trying to print any of those, all of them return nil.
Any ideas what I am doing wrong, and how to do this?
The reason I want to do this is because I want to add them as annotation to a MKMapView.
The first error is that the JSON initializer you are using will create a single JSON string object, it will not parse the string as JSON data:
Instead of:
let json = JSON(nearbyChargingSites.jsonString!)
you need to use:
let json = JSON(data: dataFromJSONString)
Second you need to iterate over the superchargers array to collect all the values
Try something like:
if let dataFromString = nearbyChargingSites.jsonString!.data(using: .utf8, allowLossyConversion: false) {
let json = try! JSON(data: dataFromString,options: .allowFragments)
for supercharger in json["superchargers"].arrayValue {
let jsonName = supercharger["name"].stringValue
let jsonLat = supercharger["location"]["lat"].doubleValue
let jsonLong = supercharger["location"]["long"].doubleValue
}
}
Please note that the above code does not perform error handling and will crash if values are missing from JSON.

Ignoring Firebase child

How could I query this data in this way:
I would like to ignore the CurrentSubAdministrativeArea child and iterate every each sub child and find the right userKey
Actually I'm using this code, that isnt working:
self.ref.child("Ads").child("CurrentSubAdministrativeArea")
/*HERE I would like to ignore the childs*/
.queryOrdered(byChild: "userKey").queryEqual(toValue: uid).observeSingleEvent(of:.value, with: { (snapshot) in
--
{
"Ads" : {
"CurrentSubAdministrativeArea" : {
"Mantova" : {
"-L7ymBmmbHkNfhBRte9F" : {
"cost" : 200,
"date" : 1527256922000,
"info" : "Test",
"maxLimit" : 100,
"minLimit" : 10,
"personBadType" : [ "abitudinaria", "antipatica" ],
"personGoodType" : [ "simpatica", "felice" ],
"subAdministrativeArea" : "Mantova",
"title" : "Mantova Test",
"url" : "https://firebasestorage.googleapis.com/v0/b/team-34540.appspot.com/o/Mantova%20Test?alt=media&token=3a81ed1c-ecd6-4dc0-bd7c-45e093ce8188",
"userKey" : "OsJRc98sqxPx70iqxFtoqerMzHH2",
"via" : "viale dei test"
}
},
"Milano" : {
"-L6qywMC6nxi0fJNMHba" : {
"cost" : 454,
"date" : 1528298580000,
"info" : "Di pollo",
"maxLimit" : 100,
"minLimit" : 10,
"personBadType" : [ "abitudinaria", "antipatica" ],
"personGoodType" : [ "simpatica", "felice" ],
"subAdministrativeArea" : "Milano",
"title" : "Pollo 2",
"url" : "https://firebasestorage.googleapis.com/v0/b/team-34540.appspot.com/o/Pollo?alt=media&token=fc6a3ec8-5f9a-4347-bdad-2d9715af784d",
"userKey" : "OsJRc98sqxPx70iqxFtoqerMzHH2",
"via" : "viale test"
}
}
}
}
}
You could denormalize your data in such a way your query is easy to build and execute.
Together with the data structure you already have you would have another node (ie. another data structure) like
{
"AdsByUsers" : {
"OsJRc98sqxPx70iqxFtoqerMzHH2": {
"Mantova",
"Milano",
...
},
"abcde88qxPx70iqxFtoqerMzKh5": {
"Firenze",
...
}
With NoSQL database you should not hesitate to duplicate data in such a way your queries are easy and fast to execute.

Multi path update in Firebase issue with more than two locations

I'm trying to update 8 locations at a time in Firebase, using the Swift SDK. Somehow I managed to update the first two, but the other six only writes to the father node, and lost its correspondent path. Below is the data of my Firebase DB that illustrates the issue better:
{
"districts" : {
"did01" : {
"name" : "Teusaquillo",
"peopleids" : {
"stateid01" : true,
"stateid02" : true,
"stateid03" : true
},
"schools" : {
"schoolid01" : {
"location" : "norte 50 grados sur 42 ",
"name" : "Agustiniano Salitre",
"posts" : {
"eighth" : {
"nola" : "hola"
},
"eighth-KaG1PA5r7cl70FtBsE4" : "angela",
"eleventh" : {
"name" : "haka"
},
"eleventh-KaG1PA5r7cl70FtBsE4" : "angela",
"fifth" : {
"-KaG1PA5r7cl70FtBsE4" : "angela",
"dsadsad" : {
"name" : "Hola"
},
"dsfsdfdsf" : true
},
"first" : {
"1" : {
"author" : "Giovanny Piñeros",
"text" : "Test"
},
"01" : {
"author" : "Giovanny Piñeros",
"text" : "Capo"
},
"abdffg" : {
"author" : "Gio",
"text" : "hola"
},
"fdgfdg" : {
"author" : "Giovanny Piñeros",
"text" : "Hola"
},
"nfdsfds" : {
"author" : "Giovanny Piñeros",
"text" : "Vivir de lo que amo"
},
"postid01" : {
"author" : "Papa frita",
"text" : "Hola",
"topic" : "Informatics",
"year" : "first"
},
"rtyrty" : {
"author" : "Giovanny Piñeros",
"text" : "Si con headapp solo sabia manejar strings y colores, imaginate ahora lo que puedo crear"
},
"zsadsa" : {
"author" : "Gio",
"text" : "Trest"
}
},
"fourth" : {
"name" : "hqiq"
},
"fourth-KaG1PA5r7cl70FtBsE4" : "angela",
"ninth" : {
"hola" : "ahah"
},
"ninth-KaG1PA5r7cl70FtBsE4" : "angela",
"postid01" : {
"-KaG0b-X9sWXxXlXlmeK" : "angela",
"-KaG0wNu0Gz5oxu4__Ej" : "angela",
"author" : "Papa frita",
"likes" : {
"userid01" : "Giovanny Piñeros"
},
"text" : "hola",
"topic " : "Informatics",
"year" : "first"
},
"postid02" : {
"autor" : "Directive",
"text" : "Free for the day",
"topic" : "General",
"year" : "all"
},
"second" : {
"-KaFnTl89keEOx3UpnGJ" : true,
"-KaFpLsNy6z-TshUJONx" : true,
"-KaFpMwBdHqBwsq-k6i3" : true,
"-KaFpz6qwQ2uTevvpxXo" : true,
"-KaFq21Qdv-Z6KFcu8ZT" : true,
"-KaFq34fN1-ZxO0EtqEw" : true,
"-KaFv7a9JvEjPLDDzT8S" : "angela",
"-KaFw9Hb6OjIRzeP6jdk" : "angela",
"-KaFwAFvFoVEvpzaaVO2" : "angela",
"-KaFwAboyWtEOG3NU1yZ" : "angela",
"-KaFwAji3rR6e5fCHjFc" : "angela",
"-KaFwAmisIA5i4UhvcRw" : "angela",
"-KaFyJHEqDzoVoj_zUWI" : "angela",
"-KaFy_cqf1mvTxRGN5j_" : "angela",
"-KaG-_r4ql2YVc19gbkt" : "angela",
"dsfsdf" : {
"hola" : "dfsad"
}
},
"seventh" : {
"name" : "dsfhksd"
},
"sixth" : {
"name" : "haaka"
},
"tenth" : {
"name" : "hola"
},
"tenth-KaG1PA5r7cl70FtBsE4" : "angela",
"third" : {
"-KaFnTl89keEOx3UpnGJ" : true,
"-KaFpLsNy6z-TshUJONx" : true,
"-KaFpMwBdHqBwsq-k6i3" : true,
"-KaFpz6qwQ2uTevvpxXo" : true,
"-KaFq21Qdv-Z6KFcu8ZT" : true,
"-KaFq34fN1-ZxO0EtqEw" : true,
"-KaFv7a9JvEjPLDDzT8S" : "angela",
"-KaFw9Hb6OjIRzeP6jdk" : "angela",
"-KaFwAFvFoVEvpzaaVO2" : "angela",
"-KaFwAboyWtEOG3NU1yZ" : "angela",
"-KaFwAji3rR6e5fCHjFc" : "angela",
"-KaFwAmisIA5i4UhvcRw" : "angela",
"-KaFyJHEqDzoVoj_zUWI" : "angela",
"-KaFy_cqf1mvTxRGN5j_" : "angela",
"-KaG-_r4ql2YVc19gbkt" : "angela",
"-KaG0b-X9sWXxXlXlmeK" : "angela",
"-KaG0wNu0Gz5oxu4__Ej" : "angela",
"-KaG1PA5r7cl70FtBsE4" : "angela",
"author" : "hola"
},
"twelfth" : {
"name" : "haoao"
}
},
"users" : {
"userid01" : {
"likes" : {
"postid01" : true
},
"name" : "Giovanny Piñeros",
"rol" : "student",
"stateid" : "stateid01",
"year" : "first"
},
"userid03" : {
"Posts" : {
"postid01" : {
"fjsldkfj" : "nombre",
"texzto" : "fksdjh"
}
},
"name" : "Papa frita",
"rol" : "teacher"
}
}
}
}
},
"did02" : {
"name" : "Austin",
"peopleids" : {
"stateid04" : true,
"stateid05" : true,
"stateid06" : true
}
}
},
"eventos" : {
"attendiees" : {
"adshfksafjh" : "giovanny"
},
"nombre" : "fiesta"
},
"queue" : {
"specs" : {
"specstest" : 0
},
"tasks" : {
"ido" : {
"_error_details" : {
"error" : "Task was malformed",
"error_stack" : "Error: Task was malformed\n at Object.update (/Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-queue/dist/lib/queue_worker.js:453:27)\n at Ih (/Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-admin/lib/database/database.js:233:395)\n at R.h.transaction (/Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-admin/lib/database/database.js:248:466)\n at /Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-queue/dist/lib/queue_worker.js:446:30\n at c (/Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-admin/lib/database/database.js:135:58)\n at /Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-admin/lib/database/database.js:126:791\n at Ac (/Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-admin/lib/database/database.js:63:165)\n at jf (/Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-admin/lib/database/database.js:126:215)\n at hf (/Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-admin/lib/database/database.js:125:479)\n at vf (/Users/Giovanny/Dropbox/Proyectos/NotifyMe/NotifyMeServer/notifymeserver/node_modules/firebase-admin/lib/database/database.js:231:426)",
"original_task" : 0
},
"_state" : "error",
"_state_changed" : 1482958978549
}
}
},
"usuarios" : {
"hvlksdj" : {
"edad" : 26,
"nombre" : "giovanny"
}
}
}
As you can see, the child nodes postid01 and second are updated, creating a new child, but for the other locations, this doesn't happen.
Here is my code. I did the following according to the Firebase guidelines:
let ref = FIRDatabase.database().reference()
var newPost = ref.childByAutoId()
let newKey = newPost.key
let dict = ["districts/did01/schools/schoolid01/posts/fifth/\(newKey)" : "test","districts/did01/schools/schoolid01/posts/third/\(newKey)": "test",
"districts/did01/schools/schoolid01/posts/fourth\(newKey)": "test","districts/did01/schools/schoolid01/posts/postid02\(newKey)": "test",
"districts/did01/schools/schoolid01/posts/sixth\(newKey)": "test","districts/did01/schools/schoolid01/posts/seventh\(newKey)": "test",
"districts/did01/schools/schoolid01/posts/eighth\(newKey)": "test", "districts/did01/schools/schoolid01/posts/ninth\(newKey)": "test", "districts/did01/schools/schoolid01/posts/tenth\(newKey)": "test", "districts/did01/schools/schoolid01/posts/eleventh\(newKey)": "test", "districts/did01/schools/schoolid01/posts/postid04\(newKey)" : "test"]
ref.updateChildValues(dict, withCompletionBlock: {(Error,FIRDatabaseReference) in
if(Error == nil){
print("EXITO :)")
}else{
print("PAILA :(")
}
})
I've just found the error, it was so simple, i make a mistake on the dictionary. The locations that weren't updated were written like this :
"districts/did01/schools/schoolid01/posts/fourth\(newKey)": "test"
As you can see the last part is missing a "/" just before the newKey.

How to boost the closest created_at field in Elasticsearch?

I want to sort my query results following some boost rules and in the same time i want them to be sorted as possible by creation date, if i add a created_at sort, it changes everything and my results are not relevant anymore. So i guess the only way to do that is to boost created_at field (the newest has the biggest bonus in calculating score for that boost) but i dont know how to implement it. This is my query:
query = {
"query" : {
"bool" : {
"must" : [
{
"range" : {
"deadline" : {
"gte" : "2016-05-30T11:39:10+02:00"
}
}
},
{
"terms" : {
"state" : [
"open"
]
}
},
{
"query_string" : {
"query" : "chant",
"default_operator" : "AND",
"analyzer" : "search_francais",
"fields" : [
"title^6",
"description",
"brand",
"category_name"
]
}
}
]
}
},
"filter" : {
"and" : [
{
"geo_distance" : {
"distance" : "40km",
"location" : {
"lat" : 48.855736,
"lon" : 2.32927300000006
}
}
}
]
},
"sort" : [
{
"_score" : "desc"
},
#{
# "created_at" : "desc" ==> i tried this but it doesnt change results
#}
]
}
Try adding your condition in should block.
i)If the created date should be closer to come value in the search query or you have any idea on how close the date should be, give a range query.
ii) If you are not sure of all those values, decay function can be used. In this case, query shall be changed to function query.
{
"query" : {
"bool" : {
"must" : [
{
"range" : {
"deadline" : {
"gte" : "2016-05-30T11:39:10+02:00"
}
}
},
{
"terms" : {
"state" : [
"open"
]
}
},
{
"query_string" : {
"query" : "chant",
"default_operator" : "AND",
"analyzer" : "search_francais",
"fields" : [
"title^6",
"description",
"brand",
"category_name"
]
}
}
],
"should": [
{"created_at" : "condition here .. "}
]
}
},
"filter" : {
"and" : [
{
"geo_distance" : {
"distance" : "40km",
"location" : {
"lat" : 48.855736,
"lon" : 2.32927300000006
}
}
}
]
}
}

Is it possible to create Salesreceipt without product/service value through QBO API?

Is it possible to create Salesreceipt without product/service value through QBO API? I have tried through API but it's not reflecting rate value and storing description value only.
If I remove ItemRef attribute(in request body) then it's reflecting rate and amount values and it's assigning some default and random product/service.
It is possible directly in QBO UI.
Request body where only description value storing:
{
"TxnDate" : "2016-05-27",
"Line" : [ {
"Amount" : 2222.00,
"Description" : "hi chk",
"DetailType" : "ItemReceiptLineDetail",
"ItemReceiptLineDetail" : {
"ItemRef" : { },
"Qty" : 1,
"UnitPrice" : 2222
} }
],
"CustomerRef" : {
"value" : "67"
},
"CustomerMemo" : {
"value" : "Thanks for your business! We appreciate referrals!"
},
"TotalAmt": 2222.00,
"PrivateNote" : "",
"CustomField" : [ {
"DefinitionId" : "1",
"Type" : "StringType",
"StringValue" : ""
} ]
}
Request body where default product/service assigning:
{
"TxnDate" : "2016-05-27",
"Line" : [ {
"Amount" : 2222.00,
"Description" : "hi chk",
"DetailType" : "ItemReceiptLineDetail",
"ItemReceiptLineDetail" : {
"Qty" : 1,
"UnitPrice" : 2222
} }
],
"CustomerRef" : {
"value" : "67"
},
"CustomerMemo" : {
"value" : "Thanks for your business! We appreciate referrals!"
},
"TotalAmt": 2222.00,
"PrivateNote" : "",
"CustomField" : [ {
"DefinitionId" : "1",
"Type" : "StringType",
"StringValue" : ""
} ]
}
No.
QuickBooks Online does not support this.

Resources