Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calling to_json on a Hash that contains a protobuf message value raises an ArgumentError #9500

Closed
lukad opened this issue Feb 13, 2022 · 1 comment · Fixed by #9513
Closed

Comments

@lukad
Copy link
Contributor

lukad commented Feb 13, 2022

What version of protobuf and what language are you using?
Version: 3.19.4
Language: Ruby

What operating system (Linux, Windows, ...) and version?

Macos 12.0.1

What runtime / compiler are you using (e.g., python version or gcc version)

Ruby 3.1.0

What did you do?

When calling to_json on a Hash or Array that contains a protobuf message an ArgumentError is raised (Expected hash arguments. (ArgumentError)).

I've created this minimal reproducable example:

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'google-protobuf', '= 3.19.4'
end

require 'json'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file('msg.proto', syntax: :proto3) do
    add_message 'Msg' do
      optional :some_field, :string, 1, json_name: 'some_field'
    end
  end
end

Msg = ::Google::Protobuf::DescriptorPool.generated_pool.lookup('Msg').msgclass
msg = Msg.new(some_field: 'some_value')

puts msg.to_json
puts({ msg: msg }.to_json)

What did you expect to see

{"some_field":"some_value"}
{"msg": {"some_field": "some_value"}}

What did you see instead?

{"some_field":"some_value"}
/Users/luka/.asdf/installs/ruby/3.1.0/lib/ruby/gems/3.1.0/gems/google-protobuf-3.19.4/lib/google/protobuf/message_exts.rb:44:in `encode_json': Expected hash arguments. (ArgumentError)
	from /Users/luka/.asdf/installs/ruby/3.1.0/lib/ruby/gems/3.1.0/gems/google-protobuf-3.19.4/lib/google/protobuf/message_exts.rb:44:in `to_json'
	from bug.rb:24:in `to_json'
	from bug.rb:24:in `<main>'
@lukad
Copy link
Contributor Author

lukad commented Feb 16, 2022

After some digging I found out that the options being passed to #to_json are a json::Ext::Generator::State object. This class implements #to_h and can be used as Hash arguments instead of raising.

Not sure if this is the right way. Would love to get some feedback on my PR #9513 and possibly get this issue resolved.

haberman pushed a commit that referenced this issue Mar 8, 2022
…hash (#9513)

* allow encode json options to be an object that responds to to_hash

fixes #9500

* try to convert options arg to hash if it is not a hash
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants