Hi all,
I have to conevrt nested json file to csv file, how i can do it?
Please help me!
- Can you show an example of the json file?
- You can use the ‘json’ gem from the standard library. The JSON.parse reads in a JSON formatted string passed as an argument, and returns a hash:
require 'json'
JSON.parse(%q/{"hello": "world"}/) # => {"hello"=>"world"}
{
“name”: “John”,
“age”: “twenty”,
“cars”: [{
“name”: “Audi”,
“models”: [“Fiesta”, “Focus”, “Mustang”]
}, {
“name”: “BMW”,
“models”: [“X1”, “X3”, “X5”]
}, {
“name”: “Fiat”,
“models”: [“Xuva”, “Panda”]
}
]
}
i need to convert into csv
my expected output should be like this
name age c_name models
john twenty audi Fiesta
john twenty audi Focus
john twenty audi Mustang
john twenty BMW X1
john twenty BMW X3
john twenty BMW X5
john twenty Fiat Xuva
john twenty BMW Panda
The simplest thing to do is a nested loop building the table.
Suppose you have An array of records like the one you presented, named db
, What about:
table = []
db.each do |record|
record["cars"].each do |car|
car["models"].each do |model|
table << [record["name"], record["age"], car["name"], model]
end
end
end
Then write that Array table
to a CSV file.