Reputation: 1751
I have an array of arrays that I'd like to convert into json and output within another array. I have the following array:
weekdays = [["Monday",2],["Tuesday",4],["Thursday",5]]
I would like to include this array within a JSON output like so:
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...
{
"results": 2,
"data": [
["Monday", 2],
["Tuesday", 4],
["Thursday", 5]
]
}
Any help would be great!
Upvotes: 2
Views: 1473
Reputation: 1349
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}
Upvotes: 1
Reputation: 106782
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:
{ :results => weekdays.count, :data => weekdays.to_h }
Upvotes: 1