1

I parse the response:

response = JSON.parse(response.body)
p response

Output

{"PC"=>"PC087849", "COUNT"=>"72421"}
{"PC"=>"PC087302", "COUNT"=>"71546"}
{"PC"=>"PC087255", "COUNT"=>"68420"}   

Then remap the keys:

a = response.map{|s| {label: s[0], value: s[1].to_i} }
puts a

Output

{:label=>nil, :value=>0}
{:label=>nil, :value=>0}
{:label=>nil, :value=>0}

Why are the contents of the Key's nil and zero?

Thanks.

4

2 回答 2

3

的元素response是哈希,而不是数组。在哈希内寻址项目时使用整数是不正确的(除非键是实际整数)

response = [{"PC"=>"PC087849", "COUNT"=>"72421"},
{"PC"=>"PC087302", "COUNT"=>"71546"},
{"PC"=>"PC087255", "COUNT"=>"68420"}]

a = response.map{|s| {label: s['PC'], value: s['COUNT'].to_i} }
puts a
# >> {:label=>"PC087849", :value=>72421}
# >> {:label=>"PC087302", :value=>71546}
# >> {:label=>"PC087255", :value=>68420}

s[0]会给你nil,因为那个键没有元素。s[1]也会给你nil,但是你打电话#to_i就可以了。那会给你0

nil.to_i # => 0
于 2013-09-02T07:13:33.800 回答
2

每个元素都是哈希,而不是数组;使用键 ( PC, COUNT) 获取哈希值。

response = [
  {"PC"=>"PC087849", "COUNT"=>"72421"},
  {"PC"=>"PC087302", "COUNT"=>"71546"},
  {"PC"=>"PC087255", "COUNT"=>"68420"},
]
response.map { |s| {label: s['PC'], value: s['COUNT'].to_i } } 
# => [
#   {:label=>"PC087849", :value=>72421},
#   {:label=>"PC087302", :value=>71546},
#   {:label=>"PC087255", :value=>68420}
# ]
于 2013-09-02T07:13:23.937 回答