【问题标题】:How to skip attributes/key in JSON output?如何跳过 JSON 输出中的属性/键?
【发布时间】:2013-06-11 14:48:03
【问题描述】:

Images Model 包含 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"
        ]
    ]
}

【问题讨论】:

    标签: ruby-on-rails json rabl grape


    【解决方案1】:

    您可以使用将其转换为哈希

    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
    

    【讨论】:

    • 非常感谢它有效。我忽略了 JSON 中的一些属性。如何有选择地显示属性?像现在 created_at 和 updated_at 属性也正在显示。
    • 嘿,你能告诉我如何忽略一个属性/键,比如说从上面的例子中假设:file_name。所以只会显示三分之二的字段
    • 更新了答案。如果您想忽略这些属性,可以向数组添加更多属性
    猜你喜欢
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多