Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output an Array as JSON?

I have the following:

@array.inspect
["x1", "x2", "adad"]

I would like to be able to format that to:

client.send_message(s, m, {:id => "x1", :id => "x2", :id => "adad" })
client.send_message(s, m, ???????)

How can I have the @array output in the ??????? space as a ids?

Thanks

like image 503
AnApprentice Avatar asked Mar 03 '12 00:03

AnApprentice


2 Answers

{:id => "x1", :id => "x2", :id => "adad" } is not a valid hash since you have a key collision

it should look like:

{
  "ids": ["x1", "x2", "x3"]
}

Update:

@a = ["x1", "x2", "adad"]
@b = @a.map { |e| {:id => e} }

Then you can do b.to_json, assuming you have done require "json" already

like image 128
Zepplock Avatar answered Oct 04 '22 07:10

Zepplock


Well ordinarily you could do something like this:

Hash[@array.collect{|i| [:id, i]}]

But that will result in {:id => "adad"} because the first element will punch all the rest: hashes in ruby have unique keys. So I don't think there's a super awesome way to do this offhand.

like image 31
Veraticus Avatar answered Oct 04 '22 07:10

Veraticus