【问题标题】:Get specific json data rails获取特定的 json 数据轨
【发布时间】:2016-05-15 15:40:06
【问题描述】:

我有这个json数据(实际数据要长很多,所以我只需要2个)

 [
  {
    "id": 1,
    "user_id": 1,
    "event_id": 1,
    "creator_id": 1,
    "event_name": "Poker",
    "cruise_ship_name": "Royal Cruise",
  },
  {
    "id": 2,
    "user_id": 1,
    "event_id": 2,
    "creator_id": 1,
    "event_name": "Ballroom",
    "cruise_ship_name": "Celebrity Infinity",
  },
  {
    "id": 3,
    "user_id": 1,
    "event_id": 3,
    "creator_id": 1,
    "event_name": "Tennis",
    "cruise_ship_name": "Mediterranean",
  }
]

我想合并所有数据并仅获取特定字段(event_name 和 Cruise_ship_name)

所以在我最终的 json 格式中

它将是:

[
  {
   "event_name": "Mexican Fiesta",
   "cruise_ship_name": "Celebrity Infinity",
  }
]

我一直在看这个例子:

@object.to_json {:include => [ :assocation_a, :assocation_b ]} 

但不确定 :association_a 和 :association_b 是什么。

【问题讨论】:

标签: ruby-on-rails json


【解决方案1】:

假设你有一个哈希数组:

events = [
  {
    "id": 1,
    "user_id": 1,
    "event_id": 1,
    "creator_id": 1,
    "event_name": "Poker",
    "cruise_ship_name": "Royal Cruise",
  },
  ...
]

您可以遍历哈希中的每个值,只保留感兴趣的值:

events.each do |event_hash| 
   event_hash.keep_if { |key, _| [:event_name, :cruise_ship_name].include?(key) }
end

puts events

【讨论】:

    【解决方案2】:

    to_json 方法接受允许您包含特定属性的参数:

    @object.to_json(only: [:event_name, :cruise_ship_name])
    

    include: :assocation_a 对象选项,允许assocation_a 模型中的对象关联也转换为 JSON。

    【讨论】:

      猜你喜欢
      • 2016-03-10
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多