How to merge a JSON-object in Jbuilder - ruby-on-rails

I am creating a rails app with Backbone/Marionette frontend.
I want to take the JSON-object below and transform it.
This is how it looks now
[{
"total_entries": 4
},
{
"entries": [{
"user": {
"id": 1,
"fullname": "Paul Paulsen"
},
"reports": [{
"id": 1,
"name": "Anna Pearson",
"relation": "wife",
"phone": "2232",
"email": "adsas#sss.se"
}
]
},
{
"user": {
"id": 2,
"fullname": "Anna Palmgren"
},
"reports": [{
"id": 3,
"name": "Mika",
"relation": "Andersen",
"phone": "12312321",
"email": "aas#sss.se"
}]
}
]
}
]
I want to make it look like this
[{
"total_entries": 4
},
{
"entries": [{
"id": 1,
"fullname": "Paul Paulsen"
}, {
"id": 1,
"name": "Anna Pearson",
"relation": "wife",
"phone": "2232",
"email": "adsas#sss.se"
}, {
"id": 1,
"fullname": "Anna Palmgren"
}, {
"id": 3,
"name": "Mika",
"relation": "Andersen",
"phone": "12312321",
"email": "aas#sss.se"
}
]
}
]
This is the Rabl file/code I use
json.array! [0,1] do |index|
if index == 0
json.total_entries #total
else
json.entries #reports.group_by(&:user) do |user, reports|
json.user user, :id, :fullname
json.reports reports do |report|
json.extract! report, :id, :name, :relation, :phone, :email
end
end
end
end

Try this ruby snippet.
x= [{
"total_entries": 4
},
{
"entries": [{
"user": {
"id": 1,
"fullname": "Paul Paulsen"
},
"reports": [{
"id": 1,
"name": "Anna Pearson",
"relation": "wife",
"phone": "2232",
"email": "adsas#sss.se"
}
]
},
{
"user": {
"id": 2,
"fullname": "Anna Palmgren"
},
"reports": [{
"id": 3,
"name": "Mika",
"relation": "Andersen",
"phone": "12312321",
"email": "aas#sss.se"
}]
}
]
}
]
x[1][:entries] = x[1][:entries].map{|p| [p[:user], p[:reports]]}.flatten

Related

Schema definition in Swagger

I'm very new to OpenAPI and I'm using http://editor.swagger.io to design an API.
I'm stuck in Schema with a JSON looking like following
{
"CORRELATION_ID": "10",
"CONTROL":
{
"DAS_IS_RECIPIENT": "123",
"DOCTPYE": "ert",
"PROCESS_INDICATOR": "nord"
},
"HEADER":
{
"ID": "456",
"INVOICE_NUMBER": "678",
"DMS_DOC_ID": "876",
"INVOICE_DATE": "10082020"
},
"ITEMS": [
{
"SHORT_TEXT": "123",
"LSTAR": 0,
"QUANTITY": "23"
},
{
"SHORT_TEXT": "456",
"LSTAR": 234,
"QUANTITY": "21"
}
],
"DEBITOR":
{
"ID": "444",
"FIRSTNAME": "nick",
"LASTNAME": "cantre"
},
"CREDITOR":
{
"ID": "454",
"FIRSTNAME": "ava",
"LASTNAME": "pierre"
}
}
How to create a schema according to this JSON structure?

How to sum items in a List in Dart

What's the best way to sum all the "amounts" of all "expenses", for each user?
I've tried a few different things but I can't quite get it right. It should return 2 values: 20.0 and 24.90
[
{
"id": 3,
"company": {
"id": 2
},
"user": {
"id": 3,
"first_name": "Fred",
"last_name": "Smith",
"email": "asdfasf",
"is_suspended": false,
"vendor_id": "FS-100",
"username": "etytyurtyu",
"expense": [
{
"id": 7,
"date": "2019-12-14T00:00:00.000Z",
"amount": 20.0,
"payment_type": "companyAccount",
"last_modified": "2019-12-16T23:50:00.459064Z",
"receipt_uri": [
"URL8",
"URL9"
],
"user": {
"id": 3
},
"expense_type": {
"id": 4
},
"booking": {
"id": "HI-3565346"
}
}
]
}
},
{
"id": 2,
"company": {
"id": 2
},
"user": {
"id": 2,
"first_name": "Pierre",
"last_name": "XXXMar",
"email": "asdfasdfads",
"is_suspended": false,
"vendor_id": "PM-100",
"username": "asdfas",
"expense": [
{
"id": 2,
"date": "2019-12-16T00:00:00.000Z",
"amount": 12.45,
"payment_type": "provided",
"last_modified": "2019-12-16T19:01:37.092932Z",
"receipt_uri": [
"URL1"
],
"user": {
"id": 2
},
"expense_type": {
"id": 6
},
"booking": {
"id": "MU-123414"
}
},
{
"id": 5,
"date": "2019-12-08T00:00:00.000Z",
"amount": 12.45,
"payment_type": "provided",
"last_modified": "2019-12-16T23:50:00.459064Z",
"receipt_uri": [
"URL1"
],
"user": {
"id": 2
},
"expense_type": {
"id": 6
},
"booking": {
"id": "MU-123414"
}
},
{
"id": 3,
"date": "2019-12-17T00:00:00.000Z",
"amount": 20.0,
"payment_type": "companyCard",
"last_modified": "2019-12-16T19:01:37.092932Z",
"receipt_uri": [
"URL5",
"URL6"
],
"user": {
"id": 2
},
"expense_type": {
"id": 12
},
"booking": {
"id": "HI-3565346"
}
}
]
}
}
]
Thanks
You would first map the expenses amounts, then fold it into a single value, like this :
double sum = expenses.map((expense) => expense.amount).fold(0, (prev, amount) => prev + amount);
List item
For the sake of completeness: In 2021 you can replace the .fold(0, (prev, amount) => prev + amount) part by just calling .sum on the list. Just import import 'package:collection/collection.dart'; first –
tmaihoff

Woocommerce JSON data is not showing in collection view

**
i was trying to load woo commerce product list in my collection view.
i am gating data from server also able to print data. but when i go to
showing data in my collection view cell it's not showing.
**
here what i have done
var newArraivalArray = [AnyObject]()
Here i try to get Json data array
Alamofire.request("https://infinitymegamall.com/wp-json/wc/v2/products?after=2016-12-19T16:39:57-08:00", parameters:
["consumer_key":"*******", "consumer_secret":"*******"])
.responseJSON{ response in
if let json = response.result.value {
newArraivalArray = json as! [AnyObject]
print(json)
}
self.collectionView.reloadData()
}
for number of item in collectionview
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return newArraivalArray.count
}
for showing data in collection view.
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cellC = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! NewArraivelCollectionViewCell
let productName = newArraivalArray[indexPath.row]["name"]
cellC.name.text = productName as? String
return cellC
}
but i did't see any data in my collection view cell.but some how product name is not showing in my cell. i have no idea what happening.
here what error i get
Here is my json Data
[
{
"id": 57678,
"name": "Mens Formal Printed Shirt",
"slug": "mens-formal-printed-shirt-3",
"permalink": "https://infinitymegamall.com/product/mens-formal-printed-shirt-3/",
"date_created": "2018-01-10T18:29:58",
"date_created_gmt": "2018-01-10T12:29:58",
"date_modified": "2018-01-10T18:29:58",
"date_modified_gmt": "2018-01-10T12:29:58",
"type": "variable",
"status": "publish",
"featured": false,
"catalog_visibility": "visible",
"description": "<p>Code:-4105110568</p>\n",
"short_description": "<p>Code:-4105110568</p>\n",
"sku": "4105110568",
"price": "1971",
"regular_price": "",
"sale_price": "",
"date_on_sale_from": null,
"date_on_sale_from_gmt": null,
"date_on_sale_to": null,
"date_on_sale_to_gmt": null,
"price_html": "<div class=\"product-price\"><del><span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">৳ </span> 2,190.00</span></del> <ins><span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">৳ </span> 1,971.00</span></ins></div>",
"on_sale": true,
"purchasable": true,
"total_sales": 0,
"virtual": false,
"downloadable": false,
"downloads": [],
"download_limit": -1,
"download_expiry": -1,
"external_url": "",
"button_text": "",
"tax_status": "taxable",
"tax_class": "",
"manage_stock": false,
"stock_quantity": null,
"in_stock": true,
"backorders": "no",
"backorders_allowed": false,
"backordered": false,
"sold_individually": false,
"weight": "",
"dimensions": {
"length": "",
"width": "",
"height": ""
},
"shipping_required": true,
"shipping_taxable": true,
"shipping_class": "",
"shipping_class_id": 0,
"reviews_allowed": true,
"average_rating": "0.00",
"rating_count": 0,
"related_ids": [
47912,
47785,
47886,
48373,
48708
],
"upsell_ids": [],
"cross_sell_ids": [],
"parent_id": 0,
"purchase_note": "",
"categories": [
{
"id": 220,
"name": "Full Sleeve",
"slug": "full-sleeve-casual"
},
{
"id": 37,
"name": "Men",
"slug": "men"
},
{
"id": 53,
"name": "Shirt",
"slug": "shirt"
},
{
"id": 91,
"name": "Casual",
"slug": "casual"
}
],
"tags": [],
"images": [
{
"id": 57683,
"date_created": "2018-01-10T18:25:13",
"date_created_gmt": "2018-01-10T12:25:13",
"date_modified": "2018-01-10T18:25:13",
"date_modified_gmt": "2018-01-10T12:25:13",
"src": "https://infinitymegamall.com/wp-content/uploads/2018/01/Mens-Formal-Printed-Shirt-Sky-Print-4105110568-2190tk-2.png",
"name": "Mens Formal Printed Shirt-Sky Print—–4105110568—-2,190tk (2)",
"alt": "",
"position": 0
},
{
"id": 57684,
"date_created": "2018-01-10T18:25:33",
"date_created_gmt": "2018-01-10T12:25:33",
"date_modified": "2018-01-10T18:25:33",
"date_modified_gmt": "2018-01-10T12:25:33",
"src": "https://infinitymegamall.com/wp-content/uploads/2018/01/Mens-Formal-Printed-Shirt-Sky-Print-4105110568-2190tk-1.png",
"name": "Mens Formal Printed Shirt-Sky Print—–4105110568—-2,190tk (1)",
"alt": "",
"position": 1
}
],
"attributes": [
{
"id": 3,
"name": "Size",
"position": 0,
"visible": true,
"variation": true,
"options": [
"L",
"M",
"XL"
]
}
],
"default_attributes": [],
"variations": [
57682,
57680,
57681
],
"grouped_products": [],
"menu_order": 0,
"meta_data": [
{
"id": 481056,
"key": "_vc_post_settings",
"value": {
"vc_grid_id": []
}
},
{
"id": 481216,
"key": "des_content",
"value": "Code:-4105110568"
},
{
"id": 481217,
"key": "trending_product",
"value": "off"
},
{
"id": 481269,
"key": "post_views",
"value": "3"
}
],
"_links": {
"self": [
{
"href": "https://infinitymegamall.com/wp-json/wc/v2/products/57678"
}
],
"collection": [
{
"href": "https://infinitymegamall.com/wp-json/wc/v2/products"
}
]
}
},
{
"id": 57672,
"name": "Mens Formal Printed Shirt",
"slug": "mens-formal-printed-shirt-2",
"permalink": "https://infinitymegamall.com/product/mens-formal-printed-shirt-2/",
"date_created": "2018-01-10T18:12:29",
"date_created_gmt": "2018-01-10T12:12:29",
"date_modified": "2018-01-10T18:12:29",
"date_modified_gmt": "2018-01-10T12:12:29",
"type": "variable",
"status": "publish",
"featured": false,
"catalog_visibility": "visible",
"description": "<p>Code:-4105110563</p>\n",
"short_description": "<p>Code:-4105110563</p>\n",
"sku": "4105110563",
"price": "1971",
"regular_price": "",
"sale_price": "",
"date_on_sale_from": null,
"date_on_sale_from_gmt": null,
"date_on_sale_to": null,
"date_on_sale_to_gmt": null,
"price_html": "<div class=\"product-price\"><del><span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">৳ </span> 2,190.00</span></del> <ins><span class=\"woocommerce-Price-amount amount\"><span class=\"woocommerce-Price-currencySymbol\">৳ </span> 1,971.00</span></ins></div>",
"on_sale": true,
"purchasable": true,
"total_sales": 0,
"virtual": false,
"downloadable": false,
"downloads": [],
"download_limit": -1,
"download_expiry": -1,
"external_url": "",
"button_text": "",
"tax_status": "taxable",
"tax_class": "",
"manage_stock": false,
"stock_quantity": null,
"in_stock": true,
"backorders": "no",
"backorders_allowed": false,
"backordered": false,
"sold_individually": false,
"weight": "",
"dimensions": {
"length": "",
"width": "",
"height": ""
},
"shipping_required": true,
"shipping_taxable": true,
"shipping_class": "",
"shipping_class_id": 0,
"reviews_allowed": true,
"average_rating": "0.00",
"rating_count": 0,
"related_ids": [
48222,
48373,
47892,
50683,
48377
],
"upsell_ids": [],
"cross_sell_ids": [],
"parent_id": 0,
"purchase_note": "",
"categories": [
{
"id": 220,
"name": "Full Sleeve",
"slug": "full-sleeve-casual"
},
{
"id": 37,
"name": "Men",
"slug": "men"
},
{
"id": 53,
"name": "Shirt",
"slug": "shirt"
},
{
"id": 91,
"name": "Casual",
"slug": "casual"
}
],
"tags": [],
"images": [
{
"id": 57676,
"date_created": "2018-01-10T18:07:45",
"date_created_gmt": "2018-01-10T12:07:45",
"date_modified": "2018-01-10T18:07:45",
"date_modified_gmt": "2018-01-10T12:07:45",
"src": "https://infinitymegamall.com/wp-content/uploads/2018/01/Mens-Formal-Printed-Shirt-Maroon-4105110563-2190tk-2.png",
"name": "Mens Formal Printed Shirt-Maroon——4105110563—-2,190tk (2)",
"alt": "",
"position": 0
},
{
"id": 57677,
"date_created": "2018-01-10T18:08:25",
"date_created_gmt": "2018-01-10T12:08:25",
"date_modified": "2018-01-10T18:08:25",
"date_modified_gmt": "2018-01-10T12:08:25",
"src": "https://infinitymegamall.com/wp-content/uploads/2018/01/Mens-Formal-Printed-Shirt-Maroon-4105110563-2190tk-1.png",
"name": "Mens Formal Printed Shirt-Maroon——4105110563—-2,190tk (1)",
"alt": "",
"position": 1
}
],
"attributes": [
{
"id": 3,
"name": "Size",
"position": 0,
"visible": true,
"variation": true,
"options": [
"L",
"M",
"XL"
]
}
],
"default_attributes": [],
"variations": [
57673,
57674,
57675
],
"grouped_products": [],
"menu_order": 0,
"meta_data": [
{
"id": 480903,
"key": "_vc_post_settings",
"value": {
"vc_grid_id": []
}
},
{
"id": 481053,
"key": "des_content",
"value": "Code:-4105110563"
},
{
"id": 481054,
"key": "trending_product",
"value": "off"
},
{
"id": 481055,
"key": "post_views",
"value": "3"
}
],
"_links": {
"self": [
{
"href": "https://infinitymegamall.com/wp-json/wc/v2/products/57672"
}
],
"collection": [
{
"href": "https://infinitymegamall.com/wp-json/wc/v2/products"
}
]
}
}]

Reverse a nested array in Ruby

I'm attempting to take a JSON API response, with nested associated resources, and reverse the associations in a Rails app.
So, imagine I get a response like this:
{
"spenders": [
{
"id": 1,
"name": "John Doe",
"accounts": [
{
"id": 1,
"name": "Account One"
},
{
"id": 2,
"name": "Account Two"
}
]
},
{
"id": 2,
"name": "Jane Doe",
"accounts": [
{
"id": 1,
"name": "Account One"
},
{
"id": 3,
"name": "Account Three"
}
]
}
]
}
My goal is to convert this into structure like this:
{
"accounts": [
{
"id": 1,
"name": "Account One",
"spenders": [
{
"id": 1,
"name": "Stephen Margheim"
},
{
"id": 2,
"name": "Greg Barendt"
}
]
},
{
"id": 2,
"name": "Account Two",
"spenders": [
{
"id": 1,
"name": "Stephen Margheim"
}
]
},
{
"id": 3,
"name": "Account Three",
"spenders": [
{
"id": 2,
"name": "Greg Barendt"
}
]
}
]
}
Now, I can do this fairly well with iteration over the hash and building a new hash:
spenders_hash = {}
accounts.each do |account|
account.spenders.each do |spender|
if spenders_hash.key? spender.id
spenders_hash[spender.id][:accounts] << account
else
spenders_hash[spender.id] = hash_from_spender_and_account(spender, account)
end
end
end
spenders_hash
def hash_from_spender_and_account(spender, account)
{
id: spender.id,
name: spender.name,
accounts: [account],
}
end
I'm hoping to find [1] a more flexible solution that isn't reliant on knowing the key names in advance and [2] hopefully more efficient.
Thoughts?

Beautify JSON parsing with Hashie::Mash Rash?

Trying to parse some ugly JSON:
image = product.images.find { |i| i["sizeName"] == "Large" }
If I use Hashie::Mash Rash, can I make it look like this instead?
image = product.images.find { |i| i["size_name"] == "large" }
If so, why am I getting undefined method 'each_pair' for #<Array:0x007f84a0408540>? Please see https://gist.github.com/frankie-loves-jesus/6b8012f9197ca6c675a9 for a full example including a live app.
Example JSON:
{
"metadata": {
"category": {
"id": "women",
"name": "Women's Fashion"
},
"showSizeFilter": false,
"showColorFilter": true,
"offset": 0,
"limit": 20,
"total": 974184
},
"products": [
{
"id": 377083005,
"name": "BCBGeneration Women's Contrast Sleeve Trench",
"currency": "USD",
"price": 168,
"priceLabel": "$168.00",
"salePrice": 106.43,
"salePriceLabel": "$106.43",
"inStock": true,
"retailer": {
"id": "849",
"name": "Amazon.com",
"url": "http://www.shopstyle.com/browse/Amazon.com-US?pid=uid9616-726296-93"
},
"locale": "en_US",
"description": "This jacket features contrasting leather sleeves",
"brand": {
"id": "51",
"name": "BCBG MAX AZRIA",
"url": "http://www.shopstyle.com/browse/BCBG-MAX-AZRIA?pid=uid9616-726296-93"
},
"clickUrl": "http://api.shopstyle.com/action/apiVisitRetailer?id=377083005&pid=uid9616-726296-93",
"images": [
{
"sizeName": "Small",
"width": 32,
"height": 40,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a_small.jpg"
},
{
"sizeName": "Medium",
"width": 112,
"height": 140,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a_medium.jpg"
},
{
"sizeName": "Large",
"width": 164,
"height": 205,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a.jpg"
}
],
"colors": [
{
"name": "Chino"
}
],
"sizes": [
{
"name": "XX-Small"
},
{
"name": "X-Small"
}
],
"categories": [
{
"id": "raincoats-and-trenchcoats",
"name": "Raincoats & Trenchcoats"
}
]
}
]
}
This is my working code
require 'json'
require 'rash'
#json_text = <<END
{
"metadata": {
"category": {
"id": "women",
"name": "Women's Fashion"
},
"showSizeFilter": false,
"showColorFilter": true,
"offset": 0,
"limit": 20,
"total": 974184
},
"products": [
{
"id": 377083005,
"name": "BCBGeneration Women's Contrast Sleeve Trench",
"currency": "USD",
"price": 168,
"priceLabel": "$168.00",
"salePrice": 106.43,
"salePriceLabel": "$106.43",
"inStock": true,
"retailer": {
"id": "849",
"name": "Amazon.com",
"url": "http://www.shopstyle.com/browse/Amazon.com-US?pid=uid9616-726296-93"
},
"locale": "en_US",
"description": "This jacket features contrasting leather sleeves",
"brand": {
"id": "51",
"name": "BCBG MAX AZRIA",
"url": "http://www.shopstyle.com/browse/BCBG-MAX-AZRIA?pid=uid9616-726296-93"
},
"clickUrl": "http://api.shopstyle.com/action/apiVisitRetailer?id=377083005&pid=uid9616-726296-93",
"images": [
{
"sizeName": "Small",
"width": 32,
"height": 40,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a_small.jpg"
},
{
"sizeName": "Medium",
"width": 112,
"height": 140,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a_medium.jpg"
},
{
"sizeName": "Large",
"width": 164,
"height": 205,
"url": "http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a.jpg"
}
],
"colors": [
{
"name": "Chino"
}
],
"sizes": [
{
"name": "XX-Small"
},
{
"name": "X-Small"
}
],
"categories": [
{
"id": "raincoats-and-trenchcoats",
"name": "Raincoats & Trenchcoats"
}
]
}
]
}
END
hash = JSON.parse(#json_text)
#rash = Hashie::Rash.new( hash )
images = []
#rash.products.each do |product|
images << product.images.find { |i| i.size_name.downcase == "large" }
end
puts images.inspect
#[#<Hashie::Rash height=205 size_name="Large" url="http://resources.shopstyle.com/pim/7b/28/7b2894c203529b0956cdd6b760629d4a.jpg" width=164>]
It doesn't raise the error you have mentioned.
And I use
$ruby --version
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin13.0.0]
gem list --local |grep 'rash'
rash (0.4.0)
$gem list --local |grep 'hashie'
hashie (3.2.0, 2.0.5)
Could you check yours?
And, if possible, dump the json at the moment that it raises the error.

Resources