-1

I got this ruby map

top_services = [["mfemve", "12,22"], ["vmtoolsd", "5,39"], ["zabbix_agentd", "1,89"]]

I need to convert this map to a JSON object and add keys something like this

{   
   { "service_name" : "mfemve", "value" : "12,22" },
   { "service_name" : "vmtoolsd", "value" : "5,39" },
   { "service_name" : "zabbix_agentd", "value" : "1,89" }   
}

how can I do this? thanks!

Molusco
  • 13
  • 4
  • 1
    Your JSON object is incorrect because "Data is in name/value pairs". Check at https://jsonlint.com/ – zswqa Aug 02 '21 at 09:46
  • The top and bottom curly brackets `{ ... }` should probably be square brackets `[ ... ]`, since it looks like you want an array of objects. I'm also not convinced that you want JSON. A lot of novice programmers throw the term JSON around as soon as they encounter a structure like `{ "key": "value" }`. Although this example is valid JSON, it might not be JSON and could as well be a Ruby hash (depending on context). Are you sure you want a [string containing a JSON object](/q/2904131/3982562)? Or do you want a [Ruby hash](https://ruby-doc.org/core-3.0.2/Hash.html) that matches the given format? – 3limin4t0r Aug 02 '21 at 12:25

1 Answers1

0

You need the json module, then mapping using zip you can do this:

require 'json'

top_services = [["mfemve", "12,22"], ["vmtoolsd", "5,39"], ["zabbix_agentd", "1,89"]]

keys = [:service_name, :value]
res = top_services.map { |e| keys.zip(e).to_h }.to_json

res
#=> "[{\"service_name\":\"mfemve\",\"value\":\"12,22\"},{\"service_name\":\"vmtoolsd\",\"value\":\"5,39\"},{\"service_name\":\"zabbix_agentd\",\"value\":\"1,89\"}]"

Consider to review the decimal separator of your numeric data, just in case it is a float.

iGian
  • 11,023
  • 3
  • 21
  • 36