0

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.