0

I have the following array:

[ { "attributes": {
      "id":   "usdeur",
      "code": 4
    },
    "name": "USD/EUR"
  },
  { "attributes": {
      "id":   "eurgbp",
      "code": 5
    },
    "name": "EUR/GBP"
  }
]

How can I get both ids for futher processing as output?

I tried a lot but no success. My problem is I always get only one id as output:

Market.all.select.each do |market|
  present market.id
end

Or:

Market.all.each{|attributes| present attributes[:id]}

which gives me only "eurgbp" as a result while I need both ids.

3
  • 1
    That looks like a JSON array, not a Ruby array... Commented Sep 8, 2014 at 15:29
  • @Jordan - correct. Sorry for the confusion Commented Sep 8, 2014 at 15:33
  • Unless you convert your keys to symbols, JSON structures are strings and strings only for keys. Commented Sep 8, 2014 at 15:39

3 Answers 3

2

JSON#parse should help you with this

require 'json'

json = '[ { "attributes": {
             "id":   "usdeur",
             "code": 4
           },
            "name": "USD/EUR"
           },
         { "attributes": {
            "id":   "eurgbp",
            "code": 5
           },
           "name": "EUR/GBP"
         }]'

ids = JSON.parse(json).map{|hash| hash['attributes']['id'] }
#=> ["usdeur", "eurgbp"]

JSON#parse turns a jSON response into a Hash then just use standard Hash methods for access.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm going to assume that the data is JSON that you're parsing (with JSON.parse) into a Ruby Array of Hashes, which would look like this:

hashes = [ { "attributes" => { "id" => "usdeur", "code" => 4 },
             "name"       => "USD/EUR"
           },
           { "attributes" => { "id" => "eurgbp", "code" => 5 },
             "name"       => "EUR/GBP"
           } ]

If you wanted to get just the first "id" value, you'd do this:

first_hash = hashes[0]
first_hash_attributes = first_hash["attributes"]
p first_hash_attributes["id"]
# => "usdeur"

Or just:

p hashes[0]["attributes"]["id"]
# => "usdeur"

To get them all, you'll do this:

all_attributes = hashes.map {|hash| hash["attributes"] }
# => [ { "id" => "usdeur", "code" => 4 },
#      { "id" => "eurgbp", "code" => 5 } ]

all_ids = all_attributes.map {|attrs| attrs["id"] }
# => [ "usdeur", "eurgbp" ]

Or just:

p hashes.map {|hash| hash["attributes"]["id"] }
# => [ "usdeur", "eurgbp" ]

Comments

0

JSON library what using Rails is very slowly...

I prefer to use:

gem 'oj'

from https://github.com/ohler55/oj

fast and simple! LET'S GO!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.