【问题标题】:Get particular key's and value's from JSON array - Ruby [duplicate]从 JSON 数组中获取特定的键和值 - Ruby [重复]
【发布时间】:2016-04-25 10:04:19
【问题描述】:

我是 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(?)

感谢您的帮助。

【问题讨论】:

  • 一个非常重要的要理解的是JSON仅仅是一种序列化机制,在操作表示为JSON的对象时,你应该反序列化它们(使用JSON.parse),并且对创建的任何 Ruby 对象进行操作。然后,如果您需要 JSON,可以使用 #to_json 或 JSON.pretty_generate 创建修改后的 JSON。所以最好考虑“JSON representation of an array*”而不是“JSON array”。

标签: ruby json


【解决方案1】:

看看这个,你应该可以解决这个问题:

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

【讨论】:

  • 感谢@Alfie,对 ruby​​ 提供的方法还不是很熟悉。
  • 输出[:elements].each 做 |item| item.keep_if{|k,_| %i(accountName lastName firstName id).include? k } 结束
  • 另外,如果你使用 Rails,你可以output["elements"].slice("accountName", "lastName", "firstName", "id")。原来slice 现在包含在 Ruby 2.5 中 – bugs.ruby-lang.org/issues/8499
猜你喜欢
  • 1970-01-01
  • 2020-01-06
  • 2017-06-16
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多