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?
Related
I need to build a json object inside a loop using params.
My params look like this...
params[:answers]
returns => {"1"=>"answer1", "2"=>"answer2"}
The keys in this json object are the id's of the survey question.
So I planed to loop through the keys to build the json object like this...
def build_answersheet_json(params[:answers], params[:survey_id])
params[:answers].keys.each do |question_id|
current_question = question_id
current_answer = params[:answers][question_id]
end
end
Since im using "t.json" in my migration to save json to postgres, I wanted to use the extracted question_id and answer to build a json object that looks something like this...
{
survey_id: '1',
answers: {
question: [{
question_id: 1,
answer: 'answer1'
}, {
question_id: 2,
answer: 'answer2'
}]
}
}
Ive been trying to do this using a method that looks somthing like this...
build_answersheet_json(params[:answers], params[:survey_id])
Ive tried JSON.parse() and Ive tried to just logically work through it but I cant seem to figure this out.
Any help is appreciated.
Maybe you can try something like that:
/* fake params (to test) */
params = {
survey_id: '1',
answers: {
"1"=>"answer1",
"2"=>"answer2",
"3"=>"answer3",
"4"=>"answer4"
}
}
def build_answersheet_json(answers, survey_id)
{
survey_id: survey_id,
answers: answers.map { |k,v| { question_id: k.to_i, answer: v } }
}
end
survey = build_answersheet_json(params[:answers], params[:survey_id])
puts survey.class
#Hash
puts survey.to_json
# formated JSON string:
# {
# "survey_id":"1",
# "answers":[
# {"question_id":1,"answer":"answer1"},
# {"question_id":2,"answer":"answer2"},
# {"question_id":3,"answer":"answer3"},
# {"question_id":4,"answer":"answer4"}
# ]
# }
In order to save to a t.json postgress column type, just pass the Hash survey object, like that:
YourModel.create(survey: survey)
Source: http://edgeguides.rubyonrails.org/active_record_postgresql.html
Try
{
survey: ¯\_༼◉ل͟◉༽_/¯,
}
Json may not be parsed if json have construction like this:
survey = {
}
Json may not contain = and assignment
Check real variables values with puts varname.inspect near at code lines where you meet unexpected behaviour.
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]
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.
I am trying to restructure a named-JSON response to return a model object (some attributes only), and some associated arrays stored in local variables, however I am unsure what I'm doing incorrectly. The local variables are definitely being assigned with values, however they're not being returned in the response.
This is the structure of what I want returned...
{ name: "Dan", email: "email#email.com", id: "1", open_gifts: [ { objects }, { here }] }
Setup
#person = Person.find_by_id(params[:id])
gifts_created_open = Gift.created_gifts_open(#person)
return_object = [#person.name, #person.email, #person.id, gifts_created_open]
Now this, returns a JSON object with the details, but its wrapped in an array, and I'm trying to return just a named object, with the associated array inside it.
render :json => return_object
And this returns a named object, but its missing the array. What gives??
render :json => #person.to_json(:gifts_created_open, :only => [:name, :email, :id] )
Many thanks with this. I've already spent several hours :/
Try:
return_object = {name:#person.name, email:#person.email, id:#person.id, gifts:gifts_created_open}.to_json
I need to bring an array of ruby objects in JSON. I will need to find the item in the JSON object by id, so I think it is best that the id is the key of each object. This structure makes the most sense to me:
{
"1": {"attr1": "val1", "attr2": "val2"},
"2": {"attr1": "val1", "attr2": "val2"},
"3": {"attr1": "val1", "attr2": "val2"}
}
That way I can easily call into the json object like console.log(json_obj[id].attr1)
The issue is that I am not quite sure how to build this in ruby. This is as far as I have gotten:
# in ruby
#book_types = []
BookType.all.each do |bt|
#book_types << {bt.id => {:attr => bt.attr}}
end
#book_types = #book_types.to_json
// In JS
var bookTypes = JSON.parse('<%=raw #book_types %>');
2 questions: How can I build this in ruby? Is there a better way to accomplish what I am doing?
Also just a note that I am building this on the Rails framework
Thanks!
Assuming BookType is an ActiveRecord class, you can just do this:
BookType.all(:select => "attr1, attr2").to_json
...where "attr1, attr2" is a list of the attributes you want to include in your JSON.
If you want the ids as keys, you can do this instead:
BookType.all.inject({}) { |hsh, bt|
hsh[bt.id] = { "attr1" => bt.attr1, "attr2" => bt.attr2 }
hsh
}.to_json