获取特定密钥';s与价值';JSON数组中的s-Ruby
我是Ruby的初学者,我有以下Json数组:获取特定密钥';s与价值';JSON数组中的s-Ruby,ruby,json,Ruby,Json,我是Ruby的初学者,我有以下Json数组: "elements": [ { "type": "Contact", "id": "1", "createdAt": "131231235", "name": "test", "updatedAt": "1456328049", "accountName": "Mr Test",
"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(?)
谢谢您的帮助。查看此项,您应该能够从中得出以下结论:
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
看看这个,你应该能够从中得出:
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提供的方法。output[:elements]。每个do | item | item。keep(u if{k,|%i(accountName lastName firstName id)。include?k}end另外,如果您使用Rails,您可以
输出[“elements”]。切片(“accountName”、“lastName”、“firstName”、“id”)
。原来slice
现在已经包含在Ruby 2.5中了——谢谢@Alfie,还不太熟悉Ruby提供的方法。output[:elements]。每个do | item | item。keep_if{k,|%i(accountName lastName firstName id)。include?k}endo另外,如果你使用Rails,你可以output[“elements”]。slice(“accountName”,“lastName”,“firstName”,“id”)
。事实证明,Ruby 2.5中包含了slice
——需要了解的一件非常重要的事情是,JSON仅仅是一种序列化机制,当操作以JSON表示的对象时,应该对其进行反序列化(使用JSON.parse),并对创建的任何Ruby对象进行操作。然后,如果需要JSON,可以使用#to#JSON或JSON.pretty_generate创建修改后的JSON。因此,最好考虑“数组的JSON表示*”而不是“JSON数组”“。需要了解的一件非常重要的事情是,JSON仅仅是一种序列化机制,当操作以JSON表示的对象时,应该对它们进行反序列化(使用JSON.parse),并对创建的任何Ruby对象进行操作。然后,如果您需要JSON,可以使用#tou JSON或JSON.pretty_generate创建修改后的JSON。因此,最好考虑“数组的JSON表示*”而不是“JSON数组”。