Best way to reformat json in Rails?
An app I am building receives some information in JSON, however the data is very poorly organized. I would like to rebuild the JSON output. The JSON I'm receiving is completely flat, and certain things should be nested. To illustrate what I mean:
I'm getting something like this:
{[
{fullname: 'Joe', session: 'A', time: '5:00', room: 'Ballroom'},
{fullname: 'Abe', session: 'B', time: '5:00', room: 'Bathroom'},
{fullname: 'Mike', session: 'C', time: '6:00', room: 'Bathroom'},
]}
I want something like this:
{
rooms: [
{
name: 'Ballroom',
sessions: [
{
title: 'A',
speakers: [{name: 'Joe'}]
}
]
},
{
name: 'Bathroom',
sessions: [
{
title: 'B',
speakers: [{name: 'Abe'}]
},
{
title: 'C',
speakers : [{name: 'Mike'}]
}
]
}
]
}
Are there any gems that are well equipped for doing something like this? Is there a specific part of the application this manipulation should be done in to follow MVC?
I should note that all this app does is receive this JSON and then makes API calls to another application to create/update information in that app's DB to reflect what's in the JSON.
Use:
JSON.pretty_generate your_hash
For example:
require 'json'
my_json = { :array => [1, 2, 3, { :sample => "hash"} ], :foo => "bar" }
puts JSON.pretty_generate(my_json)
refer to: How can I "pretty" format my JSON output in Ruby on Rails?
You can re-format using jbuilder or rabl gems. Usage and examples are pretty strait forward in their readme
链接地址: http://www.djcxy.com/p/47170.html上一篇: Ruby在JSON中解码\ n \ r