在Ruby中将JSON转换为多维数组

时间:2015-03-01 09:18:15

标签: ruby json

如何将一串JSON数据转换为多维数组?

# Begin with JSON
json_data = "[
  {"id":1,"name":"Don"},
  {"id":2,"name":"Bob"}, 
  ...
]"

# do something here to convert the JSON data to array of arrays.

# End with multidimensional arrays
array_data = [
  ["id", "name"],
  [1,"Don"],
  [2,"Bob"],
  ...
]

3 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

require 'json'
json_data = '[{"id":1,"name":"Don"},{"id":2,"name":"Bob"}]'
JSON.parse(json_data).inject([]) { |result, e| result + [e.keys, e.values] }.uniq

首先,我们将JSON读入一个JSON.parse的数组中。对于JSON中的每个元素,我们使用inject收集所有键和值,从而生成以下数组:

[
  ["id", "name"],
  [1, "Don"],
  ["id", "name"],
  [2, "Bob"]
]

为了摆脱重复的键阵列,我们调用uniq并完成。

[
  ["id", "name"],
  [1, "Don"],
  [2, "Bob"]
]

答案 1 :(得分:2)

为了便于阅读和提高效率,我会这样做:

require 'json'

json_data = '[{"id":1,"name":"Don"},{"id":2,"name":"Bob"}]'

arr =  JSON.parse(json_data)
  #=> "[{\"id\":1,\"name\":\"Don\"},{\"id\":2,\"name\":\"Bob\"}]"
keys = arr.first.keys
  #=> ["id", "name"]
arr.map! { |h| h.values_at(*keys) }.unshift(keys)
  #=> [["id", "name"], [1, "Don"], [2, "Bob"]] 

答案 2 :(得分:0)

添加@ tessi的答案,如果我们结合'with_index'和'inject',我们可以避免使用'uniq'。

require 'json'
json_data = '[{"id":1,"name":"Don"},{"id":2,"name":"Bob"}]'
array_data =  JSON.parse(json_data).each.with_index.inject([]) { |result, (e, i)|  result + (i == 0 ? [e.keys, e.values] : [e.values]) }
puts array_data.inspect

结果是:

[["id", "name"], [1, "Don"], [2, "Bob"]]