adbarads
adbarads

Reputation: 1303

Ruby converting array to hash object to json

I have an array that is dynamically created and looks like this:

 ids =  [111,333,888]

I am trying to create a json object that looks like this ultimately:

{
    "cars": [{
        "id": "111"
    }, {
        "id": "333"

    }, {
        "id": "888"
    }]
}

So I tried this while testing in the repl:

cars_object.merge!(cars: [id: ids]).to_json

that does not work. I dunno how the best way to do this. do I need to iterate through the array?

Upvotes: 0

Views: 1135

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110675

I suggest you use the method Array#product.

{ "cars": ["id"].product(ids).map { |k,v| { k=>v } } }
  #=> {:cars=>[{"id"=>111}, {"id"=>333}, {"id"=>888}]} 

or

{ "cars": ["id"].product(ids).map { |a| [a].to_h } }
  #=> {:cars=>[{"id"=>111}, {"id"=>333}, {"id"=>888}]} 

and then apply to_json.

Upvotes: 1

Kevin P
Kevin P

Reputation: 106

So, it wasn't quite clear if you wanted to convert your ids to strings or not. I assumed not but if you want to have them as strings, just add a .to_s to the i call in the map.

So, working backwards from the output, I see you have a hash with one key, value is an array of hashes of key id. From that, I make an equivalent ruby structure, hash => arrays of hashes.

require 'json'
{ cars: [111,333,888].map do |i| 
    { id: i } 
  end 
}.to_json
 => "{\"cars\":[{\"id\":111},{\"id\":333},{\"id\":888}]}"

If you're in rails, you don't need to require json.

With ruby, since everything is an object you can make this into effectively a one-liner. Given the lack of context, I can't say whether that makes sense or not.

If you're in an object, you might want to factor out the building of the id hashes into a new method and call that. If it's Rails and the ids are actually in an ActiveRecord relationship that you're grabbing, you can do something like this:

{ users: User.select(:id).first(3) }.to_json
  User Load (0.3ms)  SELECT  `users`.`id` FROM `users`  ORDER BY `users`.`id` ASC LIMIT 3
=> "{\"users\":[{\"id\":1},{\"id\":2},{\"id\":3}]}"

Obviously not a perfect match to your case but you should be able to run from there.

Upvotes: 1

nikkypx
nikkypx

Reputation: 2005

Maybe this will help.

You could create that hash like this.

car_hash = {:cars => (['id']*(ids.size)).zip(ids).map {|k, v| { k => v} }}

You could convert that to json like this.

require 'json'
car_hash.to_json

Upvotes: 0

Related Questions