Project

General

Profile

Actions

Bug #11059

closed

When saving a hash to YAML or JSON the default value isn't stored

Added by Anonymous over 9 years ago. Updated over 5 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 2.2.1p85 (2015-02-26 revision 49769) [i686-linux]
[ruby-core:<unknown>]

Description

I tried to serialize/save a hash to a YAML file, with YAML.dump. My hash has a default value set in. When I read the hash back with YAML.load, the default value is lost, because it wasn1t stored in the YAML file. I experienced the same issue using JSON.

require "yaml"
hash={"a"=>0.3,"b"=>0.7}
hash.default=1.0
File.write("hash.yaml",YAML.dump(hash))
hash2=YAML.load(File.read("hash.yaml"))
puts hash2.default
=> nil

Updated by shishir127 (Shishir Joshi) over 9 years ago

JSON is based on JavaScript and the JavaScript default value for hashes can't be changed. The YAML spec says
These primitives were chosen because they are both powerful and familiar: the sequence corresponds to a Perl array and a Python list, the mapping corresponds to a Perl hash table and a Python dictionary.

Python doesn't have a default value for dictionaries and I don't know Perl. It looks like the default value cannot be converted to YAML or JSON to maintain interoperability with other languages.

Actions #2

Updated by jeremyevans0 (Jeremy Evans) over 5 years ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0