Project

General

Profile

Actions

Bug #18167

closed

JSON.load doesn't symbolize names

Added by yann.gouverneur (Yann Gouverneur) over 2 years ago. Updated over 2 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-linux]
[ruby-core:105250]

Description

As per the documentation the JSON#load method should accept and use the same parsing options as the JSON#parse one.

Obviously this is not the case:

 $ ./json_parse_vs_load.rb
JSON.load, no symbolize => OK
{"a"=>1, "b"=>2}
JSON.load, symbolize => KO: keys are not symbols
{"a"=>1, "b"=>2}
JSON.load, no symbolize => OK
{"a"=>1, "b"=>2}
JSON.load, do symbolize => OK
{:a=>1, :b=>2}

Either the behavior with parsing options is different between these two methods and the documentation should be updated accordingly or there's a bug in the JSON#load method.

Expecting to have either the documentation updated or the incorrect behavior fixed.


Files

json_parse_vs_load.rb (669 Bytes) json_parse_vs_load.rb yann.gouverneur (Yann Gouverneur), 09/14/2021 12:56 PM

Updated by Hanmac (Hans Mackowiak) over 2 years ago

The Problem lies in the documentation of the load method:
JSON.load(source, proc = nil, options = {}) -> object

because it isn't coded for newer ruby using **options there,
for you to make it work you need:

JSON.load( source, null, symbolize_names: true )

Updated by jeremyevans0 (Jeremy Evans) over 2 years ago

  • Status changed from Open to Closed

@Hanmac (Hans Mackowiak) is correct. I think you also need to manually set create_additions: false, otherwise, an ArgumentError is raised:

JSON.load(%( {"a": 1, "b": 2} ), nil, symbolize_names: true, create_additions: false)
# => {:a=>1, :b=>2}

As this isn't a bug, I'm going to close this now. If you would like the JSON.load API changed from an options hash to keywords, you should probably file a pull request upstream: https://github.com/flori/json/pulls

Actions

Also available in: Atom PDF

Like0
Like0Like0