I have two objects, an @article and a @profile. Article is a model and @profile is a Struct. I’d like to end up with some JSON that looks like this:
{
"article": {
"title": "this is a title",
"author": "Author McAuthor",
"profile": {
"first_name": "Bobby",
"last_name": "Fisher"
}
}
}
As of now, I can just manually create this by doing something like:
@json = { article: { title: @article.title, author: @article.author, profile: { first_name: @profile.first_name, last_name: @profile.last_name } }}
I feel like building the json object this way is sorta crude, also, every time I change the author model, I might have to change this code. It would be great if I could find an easier way to build these json objects without having to do so manually… Any help? Thanks!
In addition to shioyama’s correct answer, you can use rabl to craft your JSON objects, similar to how ERB works for views.
For example, you would create a ‘view’, say,
index.rabl. It would look like: