从JSON数组中获取特定的键和值 - Ruby

时间:2016-04-25 10:04:20

标签: ruby json

我是Ruby的初学者,我有以下Json数组:

    "elements": [
        {
          "type": "Contact",          
          "id": "1",
          "createdAt": "131231235",
          "name": "test",
          "updatedAt": "1456328049",
          "accountName": "Mr Test",
          "country": "China",
          "firstName": "Test",
          "lastName": "lastNameTest",
        },
        {
          "type": "Contact",          
          "id": "2",
          "createdAt": "156453447",
          "name": "test2",
          "updatedAt": "124464554",
          "accountName": "Mr Test2",
          "country": "Germany",
          "firstName": "Test2",
          "lastName": "lastNameTest2",
            },...
]

我想只过滤掉几个键+值:例如,我想只返回id,name,accountName,firstname和lastname。

所以预期的输出如下:

    "elements": [
        {         
          "id": "1",
          "name": "test",
          "accountName": "Mr Test",
          "firstName": "Test",
          "lastName": "lastNameTest",
        },
        {      
          "id": "2",
          "name": "test2",
          "accountName": "Mr Test2",
          "firstName": "Test2",
          "lastName": "lastNameTest2",
            },...
]

我尝试了以下操作:创建一个过滤器数组,其中包含我想要返回的元素,然后映射项目,但后来我卡住了..

filters = []
filters.push("accountName")
filters.push("lastName")
filters.push("firstName")
filters.push("Id")

output["elements"].each do |item|
result = []
item.map {|key,value|filters.include? key}
result.push(?)

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

检查一下,你应该可以解决这个问题:

output = { "elements": [
          {
            "id": "1",
            "name": "test",
            "accountName": "Mr Test",
            "firstName": "Test",
            "lastName": "lastNameTest",
            "somethoong": "sdsad"
          },
          {
            "id": "2",
            "name": "test2",
            "accountName": "Mr Test2",
            "firstName": "Test2",
            "lastName": "lastNameTest2"
            }
          ]}

attribs = %w(accountName lastName firstName id)
output[:elements].each do |item|
  item.delete_if{|k,v| !attribs.include?(k.to_s)}
end