I need to avoid having null fields when rendering a JSON from a Ruby-on-Rails
API:
def index
@items = Item.all
render json: @items,
end
If my Item objects contain nil fields, they are serialized as null in the JSON. I'd just like to eliminate the null fields from my JSON.
Is there any option to render
for this purpose?
EDIT: Sample output
[{
"id": 2,
"code": "code",
"list_id": 1,
"created_by": "me",
"comment": null
}]
EDIT: Duplicate of this post ?
The post mentionned has an answer that is not really generic. I'd like to find a solution that would be appliable anywhere with a simple parameter on the render
(let's say some skip_nil_values
parameter, for example). The answer to this post nor doesn't mention how to do it, neither how to handle systematically nested objects in the returned JSON.
I'd like to avoid having bloated as_json
everywhere in my API, each time redefined manually for each new endpoint.
As a last argument, the mentionned post is refering to Rails 3.2
. I'm in Rails 5.2
. There may be some improvements between these two versions.
There is a compact method in Rails that returns a hash with non nil values. You may use: @items.map(&:compact)
Create the following private method in your application controller (name it whatever you want).
def format_collection obj_col
obj_col.as_json.each do |obj|
obj.reject! { |key, value| value.nil? }
end
end
Replace your render line with the following.
render json: format_collection @items
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.