0

我正在阅读这样的 JSON:

[
  {
    "Low": 8.63,
    "Volume": 14211900,
    "Date": "2012-10-26",
    "High": 8.79,
    "Close": 8.65,
    "Adj Close": 8.65,
    "Open": 8.7
  },
  {
    "Low": 8.65,
    "Volume": 12167500,
    "Date": "2012-10-25",
    "High": 8.81,
    "Close": 8.73,
    "Adj Close": 8.73,
    "Open": 8.76
  },
  {
    "Low": 8.68,
    "Volume": 20239700,
    "Date": "2012-10-24",
    "High": 8.92,
    "Close": 8.7,
    "Adj Close": 8.7,
    "Open": 8.85
  },
  {
    "Low": 8.78,
    "Volume": 23433900,
    "Date": "2012-10-23",
    "High": 8.94,
    "Close": 8.78,
    "Adj Close": 8.78,
    "Open": 8.93
  }
]

使用这个:

json = File.read("#{symbols[0]}.json")

然后这样做:

result = JSON.parse(json)

然后,当我想为键值“Low”选择第一个值时,我这样做了:

puts result[0]['Low']

这返回 58.75(正确)。

但我想获得“低”的前三个值。我尝试执行以下操作,但它不起作用(说不能将字符串转换为整数)。为什么?

puts result[0..2]['Low']
4

3 回答 3

1
results = [
  {"Low"=>58.75, "Volume"=>163200, "Date"=>"1962-02-01", "High"=>59.63, "Close"=>59.38, "Adj Close"=>0.61, "Open"=>59.63},
  {"Low"=>59.63, "Volume"=>134400, "Date"=>"1962-01-31", "High"=>60.0, "Close"=>59.75, "Adj Close"=>0.62, "Open"=>59.88},
  {"Low"=>59.13, "Volume"=>91200, "Date"=>"1962-01-26", "High"=>59.38, "Close"=>59.38, "Adj Close"=>0.61, "Open"=>59.13},
  {"Low"=>59.13, "Volume"=>91200, "Date"=>"1962-01-25", "High"=>59.88, "Close"=>59.13, "Adj Close"=>0.61, "Open"=>59.75},
  {"Low"=>58.5, "Volume"=>110400, "Date"=>"1962-01-24", "High"=>60.13, "Close"=>59.75, "Adj Close"=>0.62, "Open"=>60.13}
]
results[0..2].collect {|element| element['Low']}
>> [58.75, 59.63, 59.13]
于 2012-10-29T09:31:08.950 回答
0

假设您有哈希数组,您可以这样做:

results = [
  {"Low"=>58.75, "Volume"=>163200, "Date"=>"1962-02-01", "High"=>59.63, "Close"=>59.38, "Adj Close"=>0.61, "Open"=>59.63},
  {"Low"=>59.63, "Volume"=>134400, "Date"=>"1962-01-31", "High"=>60.0, "Close"=>59.75, "Adj Close"=>0.62, "Open"=>59.88},
  {"Low"=>59.13, "Volume"=>91200, "Date"=>"1962-01-26", "High"=>59.38, "Close"=>59.38, "Adj Close"=>0.61, "Open"=>59.13},
  {"Low"=>59.13, "Volume"=>91200, "Date"=>"1962-01-25", "High"=>59.88, "Close"=>59.13, "Adj Close"=>0.61, "Open"=>59.75},
  {"Low"=>58.5, "Volume"=>110400, "Date"=>"1962-01-24", "High"=>60.13, "Close"=>59.75, "Adj Close"=>0.62, "Open"=>60.13}
]

(0..2).map {|idx| results[idx]['Low']} # => [58.75, 59.63, 59.13]
于 2012-10-29T09:29:07.463 回答
0

它不起作用的原因是

  • results[0]返回单个哈希(然后您可以使用字符串对其进行索引['key']
  • results[0..2]返回另一个(较小的)散列数组(您需要使用整数对其进行索引以获得单个散列)。

使用map函数 ( docs ) 可以让您获得所需的值。请注意,它是别名,collect因此您可以使用您喜欢的任何内容。在这种情况下,您正在收集一组值,因此这可能是最佳的概念拟合。

results[0..2].map {|hash| hash['Low']}
# or equivalently
results[0..2].collect {|hash| hash['Low']}
于 2012-10-29T09:48:46.113 回答