如何跳过JSON输出中的属性/键?

时间:2013-06-11 14:48:04

标签: ruby-on-rails json rabl grape

图像模型包含id,file_name和description。宝石:RABL或GRAPE

通常的输出是:

{
    "images": [
        {
            "id": 48660,
            "file_name": "9e0f6.jpg",
            "description": "View 1"
        },
        {
            "id": 48665,
            "file_name": "fd42f.jpg",
            "description": "View 2"
        },
        {
            "id": 48662,
            "file_name": "477e8.jpg",
            "description": "View 3"
        }
    ]
}

如何删除属性/键并将值转换为数组,如下所示?

{
    "images":[
        [
            48660,
            "9e0f6.jpg",
            "View 1"
        ],
        [
            48665,
            "fd42f.jpg",
            "View 2"
        ],
        [
            48662,
            "477e8.jpg",
            "View 3"
        ]
    ]
}

1 个答案:

答案 0 :(得分:0)

您可以使用

将其转换为哈希值
JSON.parse(json)

并重建没有键的json

json_hash = JSON.parse(json)

inner_array = []
json_hash["images"].each do |elem|
  inner_array << elem.collect{|key, value| value unless ["file_name"].include?(key)}
end

json_hash["images"] = inner_array
json_hash.to_json