title: Render JSON: Remove null fields
body: <p>I need to avoid having null fields when rendering a JSON from a <code>Ruby-on-Rails</code> API:</p>
  
  <pre><code>def index
    @items = Item.all
    render json: @items,
  end
  </code></pre>
  
  <p>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.</p>
  
  <p>Is there any option to <code>render</code> for this purpose?</p>
  
  <p>EDIT: Sample output</p>
  
  <pre><code>[{
      "id": 2,
      "code": "code",
      "list_id": 1,
      "created_by": "me",
      "comment": null
  }]
  </code></pre>
  
  <p>EDIT: Duplicate of <a href="https://stackoverflow.com/questions/10811628/rails-3-2-replace-null-values-with-empty-string-from-json-serialization">this post</a>?</p>
  
  <p>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 <code>render</code> (let's say some <code>skip_nil_values</code> 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.</p>
  
  <p>I'd like to avoid having bloated <code>as_json</code> everywhere in my API, each time redefined manually for each new endpoint.</p>
  
  <p>As a last argument, the mentionned post is refering to <code>Rails 3.2</code>. I'm in <code>Rails 5.2</code>. There may be some improvements between these two versions.</p>