Search code examples
arraysrubyhashaws-clis3-object-tagging

Ruby merge two arrays in specific order


I'm trying to create the "TagSet" for aws put-object-tagging with the s3api cli from a json object. I've parsed the json in to hash and that's about the most success I've had getting to that end goal.

sample json:

{ "key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4", "key5": "value5" }

End goal example:

'{"TagSet": [{ "Key": "key1", "Value": "value1" }, { "Key": "key2", "Value": "value2"}, { "Key": "key3", "Value": "value3"}, { "Key": "key4", "Value": "value4"}, { "Key": "key5", "Value": "value5"}]}'

So far I've parsed the json to a hash then split the keys and values into 2 arrays using the below:

json = '{ "key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4", "key5": "value5" }'

new_hash = JSON.parse(json)
keys = new_hash.keys
values = new_hash.values
my_keys = []
my_vals = []


keys.each do |k|
  my_keys << "--Key " + k.to_s
end

values.each do |v|
  my_vals << "--Value " + v.to_s
end

I thought then I could iterate through each of the arrays and insert them into a single array. But the output I've resulted with is a recursive list of all the keys repeated with each value.

output = []
 my_keys.each do |x|
  my_vals.each do |y|
    output << x + " " + y
  end
end

which outputs :

--Key key1 --Value value1
--Key key1 --Value value2
--Key key1 --Value value3
--Key key1 --Value value4
--Key key1 --Value value5
--Key key2 --Value value1
--Key key2 --Value value2
--Key key2 --Value value3
--Key key2 --Value value4
--Key key2 --Value value5
--Key key3 --Value value1
--Key key3 --Value value2
--Key key3 --Value value3
--Key key3 --Value value4
--Key key3 --Value value5
--Key key4 --Value value1
--Key key4 --Value value2
--Key key4 --Value value3
--Key key4 --Value value4
--Key key4 --Value value5
--Key key5 --Value value1
--Key key5 --Value value2
--Key key5 --Value value3
--Key key5 --Value value4
--Key key5 --Value value5

Any suggestions on how to create this TagSet would be appreciated!


Solution

  • require 'json'
    
    json = '{ "key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4", "key5": "value5" }'
    
    
    tagset = JSON.parse(json)
      .map { |key, value| { Key: key, Value: value } }
      # => [{"Key":"key1","Value":"value1"},{"Key":"key2","Value":"value2"},{"Key":"key3","Value":"value3"},{"Key":"key4","Value":"value4"},{"Key":"key5","Value":"value5"}]
    
    {TagSet: tagset}.to_json
      # => '{"TagSet":[{"Key":"key1","Value":"value1"},{"Key":"key2","Value":"value2"},{"Key":"key3","Value":"value3"},{"Key":"key4","Value":"value4"},{"Key":"key5","Value":"value5"}]}'