Is it possible something like this:
group.set_attribute('katalog','zmienn',{:a1 =>1,:a2 =>2})
Is it possible something like this:
group.set_attribute('katalog','zmienn',{:a1 =>1,:a2 =>2})
NO, the symbol keys cannot be saved into an attribute dictionary.
But you can use string keys in a hash and save it as a JSON string in an attribute dictionary.
(You cannot have symbol keys in a JSON (JavaScript Object Notation) string because JSON uses ‘:
’ instead of ‘=>
’.)
require 'json'
h1 = {'a1' =>1,'a2' =>2}
j1 = h1.to_json
j1.inspect
#=> "{\"a1\":1,\"a2\":2}"
grp.set_attribute('katalog','zmienn',j1)
# Later ...
j2 = grp.get_attribute('katalog','zmienn')
h2 = JSON.parse(j2) # returns a Ruby hash object
h2.inspect
#=> {"a1"=>1, "a2"=>2}
h2.class
#=> Hash
So if you still want to use symbol keys in your hash, …
EDIT: (2018-01-12) @mamjankowski …
I overlooked an option argument for
JSON.parse()
that WILL produce Ruby hashes using symbol keys.ruby_hash = JSON.parse( json_str, symbolize_names => true ) # ... or for Ruby 2+ using named argument... ruby_hash = JSON.parse( json_str, symbolize_names: true )
(Collapsed on 2018-01-12 edit. No longer valid to discussion, but perhaps of geeky interest.)
… you will need (not really) to write your own methods to convert from JSON strings and hashes. OR just string keys to / from symbol keys, like:
def symbolize_keys(hash)
h = {}
hash.each {|k,v|
h[k.to_sym]= v
}
h # return the new hash with symbol keys
end
def stringify_keys(hash)
h = {}
hash.each {|k,v|
h[k.to_s]= v
}
h # return the new hash with string keys
end
Thanks, Dan.
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.