Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I build a JSON object?

Tags:

Currently I build a JSON object by doing:

@users = User.all  @users.each do |user|   @userlist << {     :id => user.id,     :fname => user.fname,     :lname => user.lname,     :photo => user.profile_pic.url(:small)   } end 

My challenge is I now want to include records from the @contacts table that have a different set of fields than the User model.

I tried doing

@users = User.all @contacts = current_user.contacts @users << @contacts 

But that did not work. What's the best way to combine two similar models into one JSON object?

like image 957
AnApprentice Avatar asked May 02 '11 23:05

AnApprentice


People also ask

How do you create a JSON object?

String message; JSONObject json = new JSONObject(); json. put("test1", "value1"); JSONObject jsonObj = new JSONObject(); jsonObj. put("id", 0); jsonObj. put("name", "testName"); json.

What are different ways to create objects in JSON?

Creating Simple Objectsvar JSONObj = new Object(); Creation of an object with attribute bookname with value in string, attribute price with numeric value. Attribute is accessed by using '. ' Operator −

How is JSON built?

The structure of the JSON format was derived from the JavaScript object syntax. That's the only relationship between the JSON data format and JavaScript objects. JSON is a programming language-independent format. We can use the JSON data format in Python, Java, PHP, and many other programming languages.


2 Answers

json = User.all( :include => :contacts).to_json( :include => :contacts ) 

Update

Sorry, let me give a more complete answer for what you're doing...

@users = User.all( :include => :contacts ) @userlist = @users.map do |u|   { :id => u.id, :fname => u.fname, :lname => u.lname, :photo => u.profile_pic.url(:small), :contacts => u.contacts } end  json = @userlist.to_json 

Another Update

Ok, so just forget me - I was having a bad day and totally missed the point of your question. You want some JSON that includes two unrelated sets of data. All the users, and the contacts just for the current user.

You want to create a new hash for that then, something like this...

@users = User.all @userlist = @users.map do |u|   { :id => u.id, :fname => u.fname, :lname => u.lname, :photo => u.profile_pic.url(:small) } end  json = { :users => @userlist, :contacts => current_user.contacts }.to_json 
like image 127
smathy Avatar answered Oct 21 '22 17:10

smathy


  @userlist = @users.map do |u|     u.attributes.merge!(:contacts=>current_user.contacts)   end   json = @userlist.to_json 
like image 30
user1008580 Avatar answered Oct 21 '22 15:10

user1008580