M. Suurland M. Suurland - 7 months ago 32
Ruby Question

Get particular key's and value's from JSON array - Ruby

I am a beginner with Ruby, and I have the following Json array:

"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",
},...
]


I want to filter out only a few keys + values: for example I want to return only the id,name,accountName,firstname and lastname.

So the exspected output is the following:

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


I tried the following: create a filter array which has the elements I want to return and then map over the items but then I get stuck..

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


Thank you for the help.

Answer

Check this out, you should be able to work out from this:

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
Comments