Joe
Joe

Reputation: 49

How to create a JSON Array from a two-dimensional array in Ruby

I have a two-dimensional array like this:

[
  ["01fe237f804a5eff182dcded115c37d3", 0.0140845], 
  ["026e5f1f7f026bf3c763523206aa44bf", 0.03448275], 
  ["04a1c3c79773bd1ecc0372a991adc815", 0.04617604]
]

I'd like to create a hash first, then convert it to JSON, so that the result looks like the following:

[{address: "01fe237f804a5eff182dcded115c37d3", value: 0.0140845},
{address: "026e5f1f7f026bf3c763523206aa44bf", value: 0.03448275},
{address: "04a1c3c79773bd1ecc0372a991adc815", value: 0.04617604}]

Upvotes: 0

Views: 1123

Answers (2)

mbuechmann
mbuechmann

Reputation: 5770

Your desired result is still a Ruby hash. To transform it call map on the array and create a hash for each entry:

a = [
  ["01fe237f804a5eff182dcded115c37d3", 0.0140845],
  ["026e5f1f7f026bf3c763523206aa44bf", 0.03448275],
  ["04a1c3c79773bd1ecc0372a991adc815", 0.04617604]
]

a.map{ |e| {address: e[0], value: e[1]} }

This returns the desired result.

If you want to create a JSON string, require json and do the following:

require 'json'

a = [
  ["01fe237f804a5eff182dcded115c37d3", 0.0140845],
  ["026e5f1f7f026bf3c763523206aa44bf", 0.03448275],
  ["04a1c3c79773bd1ecc0372a991adc815", 0.04617604]
]

a.map{|e| {address: e[0], value: e[1]} }.to_json

This will encode the result to the following string:

"[{\"address\":\"01fe237f804a5eff182dcded115c37d3\",\"value\":0.0140845},{\"address\":\"026e5f1f7f026bf3c763523206aa44bf\",\"value\":0.03448275},{\"address\":\"04a1c3c79773bd1ecc0372a991adc815\",\"value\":0.04617604}]"

Upvotes: 2

ray
ray

Reputation: 5552

You can do as below,

require 'json'
keys = [:address, :value]
arr.map { |values| Hash[keys.zip(values)] }.to_json

Upvotes: 1

Related Questions