通过Ruby json gem访问JSON中的unkeyed元素

时间:2014-06-04 16:04:33

标签: ruby json

我正在使用Ruby json gem。

我有一个JSON响应,如下所示:

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"
    }
  }

假设我像这样啜饮JSON:

obj = JSON.parse(json)

如何访问第一个元素,以便输出

 "BTC_LTC"
"BTC_NXT"

我试过了:

obj.each do |elem|
  puts element
end

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

简而言之,如何在{“val”中访问“val”:{“key”:“value”}}?

3 个答案:

答案 0 :(得分:1)

JSON是一个键值对系统,您需要键:

obj.keys # => ["BTC_LTC", "BTC_NXT"]

答案 1 :(得分:0)

非常简单

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

答案 2 :(得分:0)

对于键值集合,each为您提供键值:

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