如何构建 JSON 对象? [英] How do I build a JSON object?

查看:38
本文介绍了如何构建 JSON 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我通过以下方式构建了一个 JSON 对象:

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

我的挑战是我现在想要包含 @contacts 表中与 User 模型具有不同字段集的记录.

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

我尝试过

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

但这没有用.将两个相似的模型组合成一个 JSON 对象的最佳方法是什么?

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

推荐答案

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

另一个更新

好吧,忘了我吧——我今天过得很糟糕,完全没有抓住你的问题的重点.您需要一些包含两组不相关数据的 JSON.所有用户,当前用户的联系人.

你想为此创建一个新的哈希,就像这样......

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

这篇关于如何构建 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆