1

I'm working with the Ruby json gem.

I have a JSON response that looks like this:

json =
  {
    "BTC_LTC": {
      "last": "0.0172",
      "lowestAsk": "0.0174",
      "highestBid": "0.0172",
      "percentChange": "-0.01189063",
      "baseVolume": "6.42658984",
      "quoteVolume": "369.67833179",
      "isFrozen": "0"
    },
    "BTC_NXT": {
      "last": "0.00011999",
      "lowestAsk": "0.00012998",
      "highestBid": "0.00010703",
      "percentChange": "0.1999",
      "baseVolume": "40.46829556",
      "quoteVolume": "354723.19760885",
      "isFrozen": "0"
    }
  }

Assuming I slurp up the JSON like so:

obj = JSON.parse(json)

how do I access the first element so that I have an output like

 "BTC_LTC"
"BTC_NXT"

I've tried:

obj.each do |elem|
  puts element
end

obj.each do |elem|
  puts obj[elem]
end

In short, how do I access "val" in {"val": {"key":"value"}}?

1
  • From next time please use this site to beautify your JSON and post here. Commented Jun 4, 2014 at 16:19

3 Answers 3

1

JSON is a key-value pair system and you want the keys:

obj.keys # => ["BTC_LTC", "BTC_NXT"]
Sign up to request clarification or add additional context in comments.

Comments

0

For key-value collections, each gives you the key and the value:

obj.each do |key, value|
    puts key
end

Comments

0

Very easy

json = '{
    "BTC_LTC": {
        "last": "0.0172",
        "lowestAsk": "0.0174",
        "highestBid": "0.0172",
        "percentChange": "-0.01189063",
        "baseVolume": "6.42658984",
        "quoteVolume": "369.67833179",
        "isFrozen": "0"
    },
    "BTC_NXT": {
        "last": "0.00011999",
        "lowestAsk": "0.00012998",
        "highestBid": "0.00010703",
        "percentChange": "0.1999",
        "baseVolume": "40.46829556",
        "quoteVolume": "354723.19760885",
        "isFrozen": "0"
    }
}'

require 'json'

obj = JSON.parse(json)
obj.each { |k, _| puts k }
# >> BTC_LTC
# >> BTC_NXT

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.