Skip to content

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

Closed
@lukad

Description

@lukad

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>'

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions