2016-05-15 65 views
1

我有这样的JSON数据(实际数据是长了不少,这就是为什么我只需要2)获取特定的JSON数据轨

[ 
    { 
    "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是。

+0

可能是这样的副本:http://stackoverflow.com/questions/6919147/restrict-specific-fields-in-the-response-of-rails-controller – Jon

回答

0

假设你有散列的数组:

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 
0

to_json方法接受参数,让你包括特定属性:

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

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