Skip to content

problem with serializing strong params (3.11.0+) #929

@ellmo

Description

@ellmo

Problem

Hello there

Seems like I have an issue with oj (after updating to 3.16.4) not properly being used in Rails when it comes to ActionController::Parameters.

Since the users params is passed further to a Sidekiq worker, Sidekiq uses JSON.generate(object) to serialize parameters.

JSON.generate is one of three different ways of doing this incorrectly:

users = params["users"]
#=> [#<ActionController::Parameters {"email"=>"[email protected]", "first_name"=>"joe", "last_name"=>"test"} permitted: false>]

JSON.generate users
#=> "[\"{\\\"email\\\"=>\\\"[email protected]\\\", \\\"first_name\\\"=>\\\"joe\\\", \\\"last_name\\\"=>\\\"test\\\"}\"]"

JSON.dump users
#=> "[\"{\\\"email\\\"=>\\\"[email protected]\\\", \\\"first_name\\\"=>\\\"joe\\\", \\\"last_name\\\"=>\\\"test\\\"}\"]"

Oj.generate users
#=> "[\"{\\\"email\\\"=>\\\"[email protected]\\\", \\\"first_name\\\"=>\\\"joe\\\", \\\"last_name\\\"=>\\\"test\\\"}\"]"

None of those approaches returns a properly serialized object.
If you try to parse it back as JSON, it will return:

reverse = Oj.load(Oj.generate users)
#=> ["{\"email\"=>\"[email protected]\", \"first_name\"=>\"joe\", \"last_name\"=>\"test\"}"]

So now, instead of an array of hashes, we end up with an array of strings. And those strings - mind you - cannot be further parsed:

reverse.map {|x| Oj.load(x)}
#=> Oj::ParseError: unexpected character (after email) at line 1, column 9 [parse.c:762]

The only module/method combination that works is:

Oj.dump users
#=> "[{\"email\":\"[email protected]\",\"first_name\":\"joe\",\"last_name\":\"test\"}]"
Oj.load _
#=> [{"email"=>"[email protected]", "first_name"=>"joe", "last_name"=>"test"}]

Question

So here's my question: Is there an option for Oj (3.16.4) and Rails 6.1+ that I'm missing?
This was working as expected up to oj 3.10.18 and it breaks with anything over that.

My current config for Oj is this:

MultiJson.use(:oj)

Oj.default_options = {
  bigdecimal_as_decimal: true,
  bigdecimal_load: :auto,
  mode: :custom,
  second_precision: ActiveSupport::JSON::Encoding.time_precision,
  time_format: :xmlschema,
  use_as_json: true,
}
Oj.optimize_rails

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions