Rails - Including a custom array in with result of render json - ruby-on-rails

I'm trying to merge a custom array with the result of render json.
render json: #value, each_serializer: JsonApi::ValueSerializer
and the array is a = [1,2,3] .
with the result of this json is it possible to append the array?
The array will be constructed into json as
"a":{"1": "one","2":"two", "3": "three"}
Normally the json value from serializer is
'{"data":{"value_id":"1","attributes {{"id": "1","email":"tech#sample.com","access_locked":false},{"id": "2","email":"tech2#sample.com","access_locked":true}}}'
The final needed result after appending "a" json with normalized value is
'{"data":{"value_id":"1","attributes {{"id": "1","email":"tech#sample.com","access_locked":false},{"id": "2","email":"tech2#sample.com","access_locked":true}}, "a":{"1": "one","2":"two", "3": "three"}}}'

Related

Rails 4 and returning JSON response: how to correctly append extra data?

I have a SQL query returns some data, here is some sample output:
[
{
"AccountCode": "111123456",
"AccountID": 123456,
"BalanceCurrent": "-8.0",
"Phone": "123456888",
}
]
This is a Hash with an array. There are times when there will be multiple hashes within the array. Just one in this example though.
As stated, this data comes directly from the database.
I have a lookup_phone method in my Customer model that runs the SQL query and then executed in the customer_controller.rb file like so:
customer_phone = Customer.lookup_phone(params[:Phone])
Now, I need to append some extra data to these hash(es) that do not come from the database, like so:
data = [
:match_found => true,
:transfer_flag => false,
:confirm_id => 2
]
This data variable needs to be WITHIN each hash object, not a separate hash object on its own.
Using a simple array concat or + always makes the data a separate hash object. I've come across some good posts saying to use reduce along with merge, but those are Hash methods, not Array methods.
If I try to set data as a Hash instead of an array, I get
no implicit conversion of Hash into Array when I try to do
customer_phone.reduce({}, :merge)
after running customer_phone += data
What is the proper way to append data to an existing Hash object?
maybe combine each and merge
base = [
{
"AccountCode": "111123456",
"AccountID": 123456,
"BalanceCurrent": "-8.0",
"Phone": "123456888",
}
]
data = {:match_found=>true, :transfer_flag=>false, :confirm_id=>2}
base.each { |el| el.merge!(data) }
#=> [{:AccountCode=>"111123456", :AccountID=>123456, :BalanceCurrent=>"-8.0", :Phone=>"123456888", :match_found=>true, :transfer_flag=>false, :confirm_id=>2}]
You can add attr_accessor to your Customer model like this
class Customer
attr_accessor :data
end
With your data array:
data_array = [
:match_found => true,
:transfer_flag => false,
:confirm_id => 2
]
Then, you can execute the query combined with each function:
customer_phone = Customer.lookup_phone(params[:Phone]).each {|e| e.data = data_array}
Access it:
customer_phone.first.data
To render json:
render json: customer_phone, methods: [:data]

Passing multiple JSON objects as a single JSON objects Rails to AngularJS

I have a function that has multiple objects. I would like to pass these objects as one JSON object from my rails app to my angularjs app
#states = State.all
#nationalities = Nationality.all
#states_nationalities = {
states: #states,
nationalities: #nationalities
}
I thought i could do this but I am getting an error. Any help is appreciated
Hash.to_json
#states_nationalities.to_json
or for rendering
render :json #states_nationalities
#states_nationalities = {
states: #states,
nationalities: #nationalities
}
The above snippet when render as JSON should output this structure (barring that there isn't data returned from the AR calls).
{
"states": [{}, {}, {}],
"nationalities": [{}, {}, {}]
}
Both keys point to an array of objects that are your states and nationalities in your app.
What's the goal for the JSON structure to look like/what's the error you're getting?

rails render extract value from json response

I have a Rails app and I am trying to render an array of items from a parsed JSON hash.
My current render statement looks like this
resp = JSON.parse(response.body)
render json: resp
I am using Typheous and this code did not work for me:
resp = JSON.parse(response.body).fetch("item")
The following is the JSON hash (the item key has many values but I'm only displaying one for brevity):
{
ebay: [{
findItemsByKeywordsResponse: [{
ack: [],
version: [],
timestamp: [],
searchResult: [{
count: "91",
item: [{
itemId: [ "321453454731" ]
}]
}]
}]
}]
}
How can I render an array of items from the parsed JSON hash?
Since there is only one value for the ebay and findItemsByKeywordsResponse keys (per the OP's comment), you could retrieve an array of items by doing something like this:
resp = JSON.parse(response.body)
resp[:ebay].first[:findItemsByKeywordsResponse].first[:searchResult].first[:item]
This will give you an array of hashes containing the itemId and any other key-value pairs.
The reason you want to include the .first (or [0]) is because based on the parsed JSON response, your hash contains an array of hashes nested all the way to the item array. If there are multiple searchResult values, you'll need to iterate through those before getting your item array.

Hash becomes array after post

I have a hash in Ruby:
params[:test]={:name=>'sharing'}
restPost(url, params)
on the other end, I output the params:
render :json=>{ :params=>params[:test] }
I get the result:
{"params":["name", "sharing"] }
It seems the hash is turned into a array. What I want is:
{"params": {"name":"sharing"}}
One way to deal with this might be to convert the array back to a Hash with Hash[], e.g.:
a = ["name", "sharing"]
h = Hash[*a]

Get a particular key value from json in ruby

[
"KEY1":{"SUB_KEY1" : "VALUE1","SUB_KEY2" : "VALUE2"},
"KEY2":{"SUB_KEY1" : "VALUE1","SUB_KEY2" : "VALUE2"}
]
The above is my json object which is coming as a response.
How do I get SUB_KEY1 of KEY1 and SUB_KEY1 of KEY2 in Ruby on Rails?
Thank you.
You need to parse the JSON object into a ruby hash. Assuming your JSON response is called res:
require 'json'
obj = JSON.parse(res)
sv1 = obj['KEY1']['SUB_KEY1']
etc.
parsed_json = ActiveSupport::JSON.decode(your_json_string)
will parse your string as
[{"KEY1"=>{"SUB_KEY1"=>"VALUE1", "SUB_KEY2"=>"VALUE2"}}, {"KEY2"=>{"SUB_KEY1"=>"VALUE1", "SUB_KEY2"=>"VALUE2"}}]
You should be able to access it using something like parsed_json[1]["KEY2"]["SUB_KEY1"]
You need to parse JSON data first. Then loop over the JSON object to access the key as follow:
#response = JSON.parse(HTTParty.get(your_url).body)
#response["data"].each do |key|
puts data[0][key]
puts data[0][key2]
end

Resources