将数组数组转换为JSON

时间:2021-11-25 20:22:03

I have an array of arrays that I'd like to convert into json and output within another array. I have the following array:

我有一个数组,我想把它转换成json并在另一个数组中输出。我有以下数组:

weekdays = [["Monday",2],["Tuesday",4],["Thursday",5]]

I would like to include this array within a JSON output like so:

我想在JSON输出中包含这个数组,如下所示:

json_output = { :results => weekdays.count, :data => weekdays }

Right now I get this, which just doesn't look right as there are not curly brackets around the "data" field...

现在我得到了这个,它看起来不正确,因为“data”字段周围没有花括号……

{
    "results": 2,
    "data": [
        ["Monday", 2],
        ["Tuesday", 4],
        ["Thursday", 5]
    ]
}

Any help would be great!

任何帮助都将是伟大的!

2 个解决方案

#1


1  

The output is correct. Curly brackets are around hashes, but your data attribute is a nested array.

输出是正确的。花括号在散列周围,但数据属性是一个嵌套数组。

If you want to convert a nested array into a hash, just call to_h on it:

如果要将嵌套数组转换为散列,只需调用to_h:

{ :results => weekdays.count, :data => weekdays.to_h }

#2


0  

Better to convert it to hash manually.

最好手工将其转换为散列。

weekdays = [["Monday",2],["Tuesday",4],["Thursday",5]]

hash_weekdays = Hash.new
weekdays.each do |item|
 hash_weekdays[item[0]] = item[1]
end

hash_weekdays #=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5}

#1


1  

The output is correct. Curly brackets are around hashes, but your data attribute is a nested array.

输出是正确的。花括号在散列周围,但数据属性是一个嵌套数组。

If you want to convert a nested array into a hash, just call to_h on it:

如果要将嵌套数组转换为散列,只需调用to_h:

{ :results => weekdays.count, :data => weekdays.to_h }

#2


0  

Better to convert it to hash manually.

最好手工将其转换为散列。

weekdays = [["Monday",2],["Tuesday",4],["Thursday",5]]

hash_weekdays = Hash.new
weekdays.each do |item|
 hash_weekdays[item[0]] = item[1]
end

hash_weekdays #=> {"Monday"=>2, "Tuesday"=>4, "Thursday"=>5}