简体   繁体   中英

How do I change nil to null before rendering JSON from a Ruby object?

I have an arel object like this:

#<Event:0x000001097d5fa0> {
                   :id => 6302,
              :zone_id => nil,
                 :date => Thu, 02 Jan 2014 09:13:17 UTC +00:00,
               :status => 1,
           :created_at => Thu, 02 Jan 2014 09:13:17 UTC +00:00,
           :updated_at => Fri, 03 Jan 2014 09:22:16 UTC +00:00,
          :description => "New alert",
        :controller_id => 699,
           :event_type => 10,
             :is_fault => false,
                :delta => true
    }

And when I render :json => result (result being a bunch of these) it prints out:

{"controller_id"=>699, "created_at"=>"2014-01-02T09:13:17Z", "date"=>"2014-01-02T09:13:17Z", "delta"=>true, "description"=>"New alert", "event_type"=>10, "id"=>6302, "is_fault"=>false, "status"=>1, "updated_at"=>"2014-01-03T09:22:16Z", "zone_id"=>nil}

And a JSON validator complains about nil not being a string. JSON would properly be null without being a string, so I thought I would just convert it and no big deal.

So I'm down the rabbit hole, and I realize I'd like to understand more about updating an object IN PLACE before doing something with it.

update_attributes will save the record back to the DB - don't want that. assign_attributes will just change the attribute value in the object - DO WANT THIS.

BUT

assign_attributes! doesn't actually replace my object and push it back into results.

So for something where I have to iterate through an array of hashes (result), I am trying to manipulate each Ruby object IN PLACE and then serve it up through render.

There could be better ways to approach this - but that is my objective. How do I change nil to null ?

You just need to call

render :json => result.to_json

It will handle all the conversion for you including nil to null eg

require 'json'

[nil].to_json
#=> "[null]"
{blah: nil}.to_json
#=> "{\"blah\":null}"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM