Pulling Data from JSON Array to make 3 different Arrays - arrays

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;
}
)
]]]

Related

Elasticsearch / Opensearch - intersection of common values in arrays

given
a = [1,2,3,4]
and
b = [1,3]
c = [5,6]
d = [1,6]
how can i find the exact number of common values of a with b,c,d in elasticsearch?
I would expect:
b -> 2
c -> 0
d -> 1
Let consider below is your elasticsearch document,
{
"b": [1,3],
"c": [5,6],
"d": [1,6]
}
Your Elasticsearch Query will looks like below:
Here, You need to use first terms aggregation and above that you need to apply sum_bucket aggregation.
{
"size": 0,
"aggs": {
"b_count": {
"terms": {
"field": "b",
"size": 10,
"include": [1,2,3,4]
}
},
"c_count": {
"terms": {
"field": "c",
"size": 10,
"include": [1,2,3,4]
}
},
"d_count": {
"terms": {
"field": "d",
"size": 10,
"include": [1,2,3,4]
}
},
"b_sum": {
"sum_bucket": {
"buckets_path": "b_count>_count"
}
},
"c_sum": {
"sum_bucket": {
"buckets_path": "c_count>_count"
}
},
"d_sum": {
"sum_bucket": {
"buckets_path": "d_count>_count"
}
}
}
}
Sample Response:
You can use value of b_sum, c_sum and d_sum from below response.
"aggregations" : {
"b_count" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : 1,
"doc_count" : 1
},
{
"key" : 3,
"doc_count" : 1
}
]
},
"d_count" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : 1,
"doc_count" : 1
}
]
},
"c_count" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [ ]
},
"b_sum" : {
"value" : 2.0
},
"c_sum" : {
"value" : 0.0
},
"d_sum" : {
"value" : 1.0
}
}

How to parse JSON data of this type to an array?

RE-fix the parsing code and got the following JSON. How do I proceed to create 2 separate arrays: one for prefcode and one for prefName?
JSON:
[
{
"prefCode" : 1,
"prefName" : "北海道"
},
{
"prefCode" : 2,
"prefName" : "青森県"
},
{
"prefCode" : 3,
"prefName" : "岩手県"
},
{
"prefCode" : 4,
"prefName" : "宮城県"
},
{
"prefCode" : 5,
"prefName" : "秋田県"
},
{
"prefCode" : 6,
"prefName" : "山形県"
},
{
"prefCode" : 7,
"prefName" : "福島県"
},
{
"prefCode" : 8,
"prefName" : "茨城県"
},
{
"prefCode" : 9,
"prefName" : "栃木県"
},
{
"prefCode" : 10,
"prefName" : "群馬県"
},
{
"prefCode" : 11,
"prefName" : "埼玉県"
},
{
"prefCode" : 12,
"prefName" : "千葉県"
},
{
"prefCode" : 13,
"prefName" : "東京都"
},
{
"prefCode" : 14,
"prefName" : "神奈川県"
},
{
"prefCode" : 15,
"prefName" : "新潟県"
},
{
"prefCode" : 16,
"prefName" : "富山県"
},
{
"prefCode" : 17,
"prefName" : "石川県"
},
{
"prefCode" : 18,
"prefName" : "福井県"
},
{
"prefCode" : 19,
"prefName" : "山梨県"
},
{
"prefCode" : 20,
"prefName" : "長野県"
},
{
"prefCode" : 21,
"prefName" : "岐阜県"
},
{
"prefCode" : 22,
"prefName" : "静岡県"
},
{
"prefCode" : 23,
"prefName" : "愛知県"
},
{
"prefCode" : 24,
"prefName" : "三重県"
},
{
"prefCode" : 25,
"prefName" : "滋賀県"
},
{
"prefCode" : 26,
"prefName" : "京都府"
},
{
"prefCode" : 27,
"prefName" : "大阪府"
},
{
"prefCode" : 28,
"prefName" : "兵庫県"
},
{
"prefCode" : 29,
"prefName" : "奈良県"
},
{
"prefCode" : 30,
"prefName" : "和歌山県"
},
{
"prefCode" : 31,
"prefName" : "鳥取県"
},
{
"prefCode" : 32,
"prefName" : "島根県"
},
{
"prefCode" : 33,
"prefName" : "岡山県"
},
{
"prefCode" : 34,
"prefName" : "広島県"
},
{
"prefCode" : 35,
"prefName" : "山口県"
},
{
"prefCode" : 36,
"prefName" : "徳島県"
},
{
"prefCode" : 37,
"prefName" : "香川県"
},
{
"prefCode" : 38,
"prefName" : "愛媛県"
},
{
"prefCode" : 39,
"prefName" : "高知県"
},
{
"prefCode" : 40,
"prefName" : "福岡県"
},
{
"prefCode" : 41,
"prefName" : "佐賀県"
},
{
"prefCode" : 42,
"prefName" : "長崎県"
},
{
"prefCode" : 43,
"prefName" : "熊本県"
},
{
"prefCode" : 44,
"prefName" : "大分県"
},
{
"prefCode" : 45,
"prefName" : "宮崎県"
},
{
"prefCode" : 46,
"prefName" : "鹿児島県"
},
{
"prefCode" : 47,
"prefName" : "沖縄県"
}
]
ViewController Code :
import UIKit
import SwiftyJSON
import Alamofire
import Foundation
struct Citys: Decodable {
let prefCode: Int
let cityName: String
let cityCode: Int
let bigCityFlag: Int
}
class ViewController: UIViewController {
#IBOutlet weak var City: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
if let BASEURL = URL(string: "https://opendata.resas-portal.go.jp/api/v1/prefectures?") {
var urlRequest = URLRequest(url: BASEURL)
urlRequest.httpMethod = HTTPMethod.get.rawValue
var headers: HTTPHeaders
if let existingHeaders = urlRequest.allHTTPHeaderFields {
headers = existingHeaders
} else {
headers = HTTPHeaders()
}
headers["X-API-KEY"] = "4GMF0uUh7T9UHFvcp8xq6r4WnGnBA6arqJpuoPIS"
//headers["Content-Type"] = "application/json;charset=UTF-8"
headers["Content-Type"] = "application/json"
headers["charset"] = "utf-8"
urlRequest.allHTTPHeaderFields = headers
let request = Alamofire.request(urlRequest)
.responseJSON { response in
//debugPrint(response)
guard let object = response.result.value else {
print("Error")
return
}
//print(response)
let propertyJSON : JSON = JSON(response.result.value!)
self.updateName(json: propertyJSON)
}
}
}
//MARK: - JSON Parsing
/***************************************************************/
func updateName(json : JSON) {
for result in json {
print(result.1)
}
First of all Benny, the data which you have provided as JSON data is not valid as JSON data. There are quite a few errors. i have listed them below:
in each key-value pair, the key and value should be separated by a colon : and not = as you have shown. For example: message = "<null>" ==> message: "<null>"
successive key-value pairs should be separated by commas and not ;. For example: bigCityFlag = 2; cityCode = 01100; ==> bigCityFlag: 2, cityCode: 01100,
Also, result is supposed to be an array of objects, I presume. If I'm right about it, then it should be enclosed within [ ] and not ( ), which would make it: result: ({ ==> result: [{.
Emmanuel has suggested a good way to make these changes. Assuming you have used this or some other approach to rectify it into valid JSON data, you could use the following approach to get the result part of it into respective arrays.
var SUCCESS = {
message: "<null>",
result: [{
bigCityFlag: 2,
cityCode: 01100,
cityName: "\U672d\U5e4c\U5e02",
prefCode: 1
}, {
bigCityFlag: 1,
cityCode: 01101,
cityName: "\U672d\U5e4c\U5e02\U4e2d\U592e\U533a",
prefCode: 1
}, {
bigCityFlag: 1,
cityCode: 01102,
cityName: "\U672d\U5e4c\U5e02\U5317\U533a",
prefCode: 1
}, {
bigCityFlag: 1,
cityCode: 01103,
cityName: "\U672d\U5e4c\U5e02\U6771\U533a",
prefCode: 1
}, {
bigCityFlag: 0,
cityCode: 47382,
cityName: "\U4e0e\U90a3\U56fd\U753a",
prefCode: 47
}]
};
var bigCityFlag = [];
var cityCode = [];
var cityName = [];
var prefCode = [];
for (var i = 0; i < SUCCESS.result.length; i++) {
bigCityFlag[i] = SUCCESS.result[i].bigCityFlag;
cityCode[i] = SUCCESS.result[i].cityCode;
cityName[i] = SUCCESS.result[i].cityName;
prefCode[i] = SUCCESS.result[i].prefCode;
}
console.log("BIG CITY FLAG = [ " + bigCityFlag + " ]");
console.log("CITY CODE = [ " + cityCode + " ]");
console.log("CITY NAME = [ " + cityName + " ]");
console.log("PREF CODE = [ " + prefCode + " ]");
This is not valid Json Data, and I wouldn't recommend using this approach. But if you had to you could parse it using regex and string replacements as follows. Considering that the $DATA variable contains what you posted above.
// Replace the following characters: ( ) = ; with these: [ ] : ,
// and escape backslashes, \ becomes \\ (also must be escaped for the str_replace call)
$DATA = str_replace(['(',')', '=', ';', '\\'], ['[',']',':', ',', '\\\\'], $DATA);
// Remove SUCCESS: from the start
$DATA = trim($DATA, 'SUCCESS:');
// Wrap keys with quotes ""
$DATA = preg_replace('/([a-zA-Z0-9]+)\s\:/', '"$1":', $DATA);
// Trim zeros from integer values
$DATA = preg_replace('/:\s[0]+[1-9]/', ': ', $DATA);
// Remove comma from last item in array
$DATA = preg_replace('/,([\r|\n|\s]+)([\[|\}|\)])/', '$1$2', $DATA);
// Decode Json
$JSON = json_decode($DATA);
// Voila!
print_r($JSON);

Swift 4 json array - how to get value

I have this code in Swift 4 and Alamofire:
Alamofire.request("http://xxxx.pl/id=1", method: .get, parameters: nil)
.responseJSON { response in
let jsonResponse = JSON(response.result.value!)
let resData = jsonResponse["ranking"].array
print("XXXX: \(jsonResponse)")
}
.responseString { response in
if let error = response.result.error {
print(error)
}
if let value = response.result.value {
print(value)
}
}
After running this code, I get a json with the following parameters:
XXXX: {
"ranking" : {
"dataWidoczneOd" : {
"second" : 0,
"year" : 2018,
"month" : 2,
"hourOfDay" : 0,
"dayOfMonth" : 1,
"minute" : 0
}
"opis" : "cx",
"id" : 50971,
"dataWidoczneDo" : {
"second" : 0,
"year" : 2018,
"month" : 2,
"hourOfDay" : 0,
"dayOfMonth" : 31,
"minute" : 0
},
"grupy" : [
{
"nazwa" : "yyy",
"kod" : "yyy",
"id" : 51032,
"idkiPlikowGrafiki" : [
"51034"
],
"gracze" : [
{
"zakonczonaGra" : false,
"imieINazwisko" : "zzzz yyyy",
"email" : "tertretera#cccc.com",
"liczbaZdobytychPunktow" : "0.0",
"czasGry" : "0 min"
}
]
},
{
"nazwa" : "ttt",
"kod" : "ttt",
"id" : 50981,
"idkiPlikowGrafiki" : [
"50983",
"50986"
],
"gracze" : [
]
}
],
"nazwa" : "grupowy",
"idkiPlikowGrafiki" : [
"50976"
],
"typ" : "GRUPA",
"dataOd" : {
"second" : 0,
"year" : 2018,
"month" : 2,
"hourOfDay" : 0,
"dayOfMonth" : 1,
"minute" : 0
}
}
}
How can I get the values from this json array and save in variables:
- gracze (all values)
- idkiPlikowGrafiki (all values)
- typ (all values)
- kod (all values)
- dataWidoczneOd (all values)
?
Please help :)
You should create a model class for this response and parse it with, for example, Codable. Here is a good example.

How to update array of embedded collection field based on another collection embedded field value in MongoDB?

I've searched in this forum for my below issue and I'm not able to find solution.
Inventory collction:
{
"_id" : ObjectId("555b1978af015394d1016374"),
"Billno" : "ABC1",
"Device_id" : "strsdedgfrtg12",
"item" : [
{
"item_id" : 232,
"size" : "S",
"qty" : 25
},
{
"item_id" : 272,
"size" : "M",
"qty" : 5
}
],
"category" : "clothing"
}
inventory_new collection:
{
"_id" : ObjectId("555b1978af015394d1016374"),
"Billno" : "ABC1",
"Device_id" : "strsdedgfrtg12",
"item" : [
{
"item_id" : 232,
"size" : "S",
"qty" : 25
},
{
"item_id" : 272,
"size" : "M",
"qty" : 5000
}
],
"category" : "clothing"
}
Now I've to update the inventory collection embedded array's item "qty" with inventory_new collections embedded item "qty" field value.. I've tried below code.. But I'm not succeed. Please advice.
db.inventory.find().forEach(function (doc1) {
var doc2 = db.inventory_copy.find({ Billno: doc1.Billno},{ Device_id: doc1.Device_id},{ item.item_id: doc1.item.item_id}, {item.qty: 1 });
if (doc2 != null) {
doc1.item.qty = doc2.item.qty;
db.inventory.save(doc1);
}
});
Thanks
Try the following update:
db.inventory.find().forEach(function (doc1) {
var doc2 = db.inventory_copy.findOne(
{
"Billno": doc1.Billno,
"Device_id": doc1.Device_id,
"item.item_id": doc1.item.item_id
}
);
if (doc2 != null) {
doc1.item = doc2.item;
db.inventory.save(doc1);
}
});

JSON array pushing

I have this example array for an entry to be inserted to a YUI datatable
var book = {
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
};
will i be able to get the same array by doing this?
var book = [];
var booktemp = {
"id" : "po-0167"
};
book.push(booktemp);
booktemp = {
"date" : new Date(1980, 2, 24)
};
book.push(booktemp);
booktemp = {
"quantity" : 1
};
book.push(booktemp);
booktemp = {
"amount" : 4
};
book.push(booktemp);
booktemp = {
"title" : "A Book About Nothing"
};
book.push(booktemp);
what i am trying here is to write a generic method that will iterate through a list of results and able to form an entry in the future.
var resultsArray = [];
for( int i = 0; i < array.features.length; i ++)
{
var resultsFeatureArray = [];
for( att in array.features[i].attributes)
{
var temp = {
att : array.features[i].attributes[att]
}
resultsFeatureArray.push(temp);
}
resultsArray.push(resultsFeatureArray);
}
so how could i make the array the same as the first segment of the book code?
added my whole sample code, the commented book array seems to work but the uncommented part seems to not be able to show the rows
<script type="text/javascript">
YAHOO.util.Event.addListener(window, "load", function() {
YAHOO.example.Data = {
bookorders: [
]
}
var bookorders = [];
/*
var book = {
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
};
*/
var book = [];
var booktemp = {
"id" : "po-0167"
};
book.push(booktemp);
booktemp = {
"date" : new Date(1980, 2, 24)
};
book.push(booktemp);
booktemp = {
"quantity" : 1
};
book.push(booktemp);
booktemp = {
"amount" : 4
};
book.push(booktemp);
booktemp = {
"title" : "A Book About Nothing"
};
book.push(booktemp);
bookorders.push(book);
YAHOO.example.Basic = function() {
var myColumnDefs = [
{key:"id", sortable:true, resizeable:true},
{key:"date", formatter:YAHOO.widget.DataTable.formatDate, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC},resizeable:true},
{key:"quantity", formatter:YAHOO.widget.DataTable.formatNumber, sortable:true, resizeable:true},
{key:"amount", formatter:YAHOO.widget.DataTable.formatCurrency, sortable:true, resizeable:true},
{key:"title", sortable:true, resizeable:true}
];
var myDataSource = new YAHOO.util.DataSource(bookorders);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
myDataSource.responseSchema = {
fields: ["id","date","quantity","amount","title"]
};
var myDataTable = new YAHOO.widget.DataTable("basic",
myColumnDefs, myDataSource);
return {
oDS: myDataSource,
oDT: myDataTable
};
}();
});
I tried and found the solution to it, since the att and values will be object after i push it
var temp = new Object();
temp["id"] = "po-0167";
temp["date"] = new Date(1980, 2, 24);
temp["quantity"] = 1;
temp["amount"] = 4;
temp["title"] = "A Book About Nothing";
bookorders.push(temp);
this will make it display in the datatable, the generic part will just be iterated through using the temp[att] = attributes[att];
var book = {
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
};
it's not array.
Array is
var books =[{
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
}]
and after manipulation in your example you will get next array
var book2 =[{
"id" : "po-0167"
},{
"date" : new Date(1980, 2, 24)
},{
"quantity" : 1
},{
"amount" : 4
},{
"title" : "A Book About Nothing"
}]
it's not the same.
You must do next:
var book = new Array();
var booktemp = {
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
};
book.push(booktemp);
PS.
var arr = [] and var arr = new Array() are the same
Not all browsers works well with var arr = []

Resources