0

How can I convert a string of JSON data to a multidimensional array?

# Begin with JSON
json_data = "[
  {"id":1,"name":"Don"},
  {"id":2,"name":"Bob"}, 
  ...
]"

# do something here to convert the JSON data to array of arrays.

# End with multidimensional arrays
array_data = [
  ["id", "name"],
  [1,"Don"],
  [2,"Bob"],
  ...
]

3 Answers 3

2

For readability and efficiency, I would do it like this:

require 'json'

json_data = '[{"id":1,"name":"Don"},{"id":2,"name":"Bob"}]'

arr =  JSON.parse(json_data)
  #=> "[{\"id\":1,\"name\":\"Don\"},{\"id\":2,\"name\":\"Bob\"}]"
keys = arr.first.keys
  #=> ["id", "name"]
arr.map! { |h| h.values_at(*keys) }.unshift(keys)
  #=> [["id", "name"], [1, "Don"], [2, "Bob"]] 
Sign up to request clarification or add additional context in comments.

Comments

2

This should do the trick:

require 'json'
json_data = '[{"id":1,"name":"Don"},{"id":2,"name":"Bob"}]'
JSON.parse(json_data).inject([]) { |result, e| result + [e.keys, e.values] }.uniq

First, we read the JSON into an array with JSON.parse. For each element in the JSON, we collect all keys and values using inject which results in the following array:

[
  ["id", "name"],
  [1, "Don"],
  ["id", "name"],
  [2, "Bob"]
]

To get rid of the repeating key-arrays, we call uniq and are done.

[
  ["id", "name"],
  [1, "Don"],
  [2, "Bob"]
]

Comments

0

Adding to @tessi's answer, we can avoid using 'uniq' if we combine 'with_index' and 'inject'.

require 'json'
json_data = '[{"id":1,"name":"Don"},{"id":2,"name":"Bob"}]'
array_data =  JSON.parse(json_data).each.with_index.inject([]) { |result, (e, i)|  result + (i == 0 ? [e.keys, e.values] : [e.values]) }
puts array_data.inspect

The result is:

[["id", "name"], [1, "Don"], [2, "Bob"]]

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.