How do I convert an array in nested hash in ruby
For example:
From
{
"errors": {
"name": [
"must be filled"
],
"type": [
"must be filled"
],
"address": {
"country_id": [
"must be filled"
]
},
"group": {
"name": [
"is missing"
]
},
"contacts": {
"2": {
"name": [
"must be filled"
],
"phone": {
"0": {
"number": [
"must be filled"
],
"email": [
"must be valid"
]
}
}
}
}
}
}
To
{
"errors": {
"name": "must be filled",
"type": "must be filled",
"address": {
"country_id": "must be filled"
},
"group": {
"name": "is missing"
},
"contacts": [
{
"name": "must be filled",
"index": 2,
"phone": [
{
"number": "must be filled",
"email": "must be valid",
"index": 0
}
]
}
}
}
I want remove key of hash ("2", "0") and convert it to hash of array. Thanks
I tried and succeeded in the following way. Thanks all
def change(messages)
result = {}
array = []
messages.each do |field, message|
if message.is_a?(Hash)
if field.is_a? Integer
value = change(message)
array.push(value.merge(index: field))
result = array
else
value = change(message)
result[field] = value
end
else
result[field] = message.at(0)
end
end
result
end
Related
I have some code that was working just fine a few months ago, but something in the Graph API has changed and this no longer works. I am trying to create a message in an existing folder, by doing a POST to this url:
https://graph.microsoft.com/v1.0/users/jjones#transend.onmicrosoft.com/mailFolders/AAMkADNjAAA=/messages
(folder id shortened)
The call fails with http error 400, and the returned error is "UnableToDeserializePostBody". The input json is shown below. By experimentation I was able to trace the problem specifically to "singleValueExtendedProperties". I normally put several properties there, but for this test I removed all but the one you see. I have tried other properties as well, they all fail. This seems like some stupid formatting error but I can't see it. Any help appreciated.
{
"subject": "Test again",
"Sender": {
"emailAddress": {
"name": "John Doe",
"address": "missing#domain.com"
}
},
"body": {
"contentType": "TEXT",
"content": "This is a text message."
},
"toRecipients": [
{
"emailAddress": {
"name": "Jane Smith",
"address": "missing#domain.com"
}
}
],
"ccRecipients": [
{
"emailAddress": {
"name": "Bob Jones",
"address": "missing#domain.com"
}
}
],
"singleValueExtendedProperties": [
{
"propertyId": "SystemTime 0x0039",
"value": "1998-07-29T21:30:00.0000+00:00"
}
],
"importance": "normal"
}
The main problem here is you are specifying the property('propertyid') in singleValueExtendedProperties object is not valid. There are only 2 properties in singleValueExtendedProperties. One is id and the other is value.
Replace 'propertyId' with id.
I have tested it in POSTMAN with your payload changing the propertyId to id and it worked.
Request Body:-
{
"subject": "Test again",
"Sender": {
"emailAddress": {
"name": "John Doe",
"address": "missing#domain.com"
}
},
"body": {
"contentType": "TEXT",
"content": "This is a text message."
},
"toRecipients": [
{
"emailAddress": {
"name": "Jane Smith",
"address": "missing#domain.com"
}
}
],
"ccRecipients": [
{
"emailAddress": {
"name": "Bob Jones",
"address": "missing#domain.com"
}
}
],
"singleValueExtendedProperties": [
{
"id": "SystemTime 0x0039",
"value": "1998-07-29T21:30:00.0000+00:00"
}
],
"importance": "normal"
}
I'm using swagger for quite a bit now, we have started documenting our code using it, in one place there's an API response which returns multiple objects in the included block.
Example:
{
"data": {
"id": "1",
"type": "schoolPositions",
"attributes": {
"description": "teases the students",
"mustHaves": "principle"
},
"relationships": {
"schoolLocation": {
"data": {
"id": "72",
"type": "schoolLocations"
}
},
"schoolCompensation": {
"data": {
"id": "75",
"type": "schoolCompensations"
}
},
"jobSpecs": {
"data": [
{
"id": "82",
"type": "schoolAttachments"
}
]
}
}
},
"included": [
{
"id": "72",
"type": "schoolLocations",
"attributes": {
"city": "Berhampore",
"state": "West Bengal",
"postalCode": "742101",
"country": "India",
"globalRegionId": 30,
"regionId": 683
}
},
{
"id": "75",
"type": "schoolCompensations",
"attributes": {
"salary": "",
"bonus": "",
"equity": "",
"currencyId": null,
"equityType": "percent",
"salaryDescription": null
}
},
{
"id": "82",
"type": "schoolAttachments",
"attributes": {
"attachmentType": "JobSpecificationAttachmentType",
"fileFileName": "vs.jpg",
"fileContentType": "image/jpeg",
"fileFileSize": 2410039,
"fileUpdatedAt": "2018-12-12T07:06:38Z",
"downloadUrl": "001-vs.jpg?1544598398",
"klass": "SchoolAttachments"
}
}
]
I have wasted an entire day on the internet and documentation trying to document the included part, but I'm going wrong somewhere
response 200 do
key :description, 'School Data'
schema do
property :data do
key :type, :array
items do
key :'$ref', :School
end
end
property :included do
key :type, :array
items do
key :'$ref', :SchoolLocations
key :'$ref', :SchoolCompensations
key :'$ref', :SchoolAttachments
end
end
end
end
This shows only the SchoolAttachments in the included part.
I have tried using allOff but it doesn't work.
Is it possible to specify the "response" based on the "consumes" option on Swagger?
My API can return "json" or "text" and I'd like that the "example value", when the response's status is 200 changes if the user selects from Response Content Type the option application/json or text/plain.
This is a piece of my swagger.json file:
{
"swagger": "2.0",
"produces": [
"application/json",
"text/plain"
],
"consumes" : [
"application\/json"
],
"paths": {
"/writer/1/": {
"get": {
"summary": "Get all writers",
"description": "Writer description.",
"tags": [
"writer"
],
"responses": {
"200": {
"description" : "successful operation",
"schema" : {
"$ref" : "#\/definitions\/writerResponse"
}
},
}
}
}
"definitions": {
"writerResponse": {
"properties": {
"meta": {
"type" :"object",
"schema" : {
"$ref" : "#\/definitions\/metaDefinition"
}
},
"data": {
"type" :"array",
"items": {
"$ref" : "#\/definitions\/writer"
}
}
}
},
"writer": {
"properties": {
"id": {
"type": "integer",
"description": "writer id.",
"example": "1477"
},
"short": {
"type": "string",
"description": "short description.",
"example": "short example"
},
"modified": {
"type": "string",
"description": "modified description.",
"example": "2016-05-21 22:58:36"
}
}
},
}
This is an example of the JSON output when user selects application/json:
{
"meta": {
"total": "1234",
"last_page": "967",
"per_page": "4000",
"current_page": "1",
"next_page_url": "http://localhost/api/<ws>/1?page=2",
"prev_page_url": "http://localhost/api/<ws>/1?page=1",
"from": "1",
"to": "4000"
},
"data": [
{
"id": "1",
"short": "TEST1",
"modified": "2011-03-07 14:17:23"
},
{
"id": "5",
"short": "TEST2",
"modified": "2015-05-26 12:39:45"
}
]
}
And this is the output when the user selects text/plain:
id|short|modified
1|TEST1|2011-03-07 14:17:23
5|TEST2|2015-05-26 12:39:45
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?
I am grabbing value data: name, uid, highschool_name, graduateschool_name like this:
def add_friends
facebook.get_connections("me", "friends", :fields => "name, id, education").each do |hash|
self.friends.where(:name => hash['name'],
:uid => hash['id'],
:highschool_name => hash['education']['school']['name'] unless hash["education"].blank?,
:graduateschool_name => hash['education']['school']['name'] unless hash["education"].blank?).
first_or_create
end
end
From an array of hash:
"education": [
{
"school": {
"id": "110703012290674",
"name": "Kunskapsgymnasiet Malmö"
},
"year": {
"id": "136328419721520",
"name": "2009"
},
"type": "High School"
},
{
"school": {
"id": "112812485399398",
"name": "Malmö University"
},
"year": {
"id": "118118634930920",
"name": "2012"
},
"concentration": [
{
"id": "104076956295773",
"name": "Computer Science"
}
],
"type": "Graduate School",
"classes": [
{
"id": "165093923542525",
"name": "Programmering",
"description": "Kursen fokuserar på metoder och tekniker vid utveckling av webbapplikationer med hjälp av HTML5."
}
]
}
],
EDIT:
This code dosent work. I would like to pick every hichschool and Graduate School from this array of hash and save it.
high_schools = response['education'].collect{|ed| ed['school']['name'] if ed['type'] == "High School" }
grad_schools = response['education'].collect{|ed| ed['school']['name'] if ed['type'] == "Graduate School" }