Why key of hash is not parsed

282 Views Asked by At

I'm working with hash like this, the first key is a hash

hash = { { a: 'a', b: 'b' } => { c: { d: 'd', e: 'e' } } }

when I convert it to json, I get this:

data_json = hash.to_json

# => "{\"{:a=\\u003e\\\"a\\\", :b=\\u003e\\\"b\\\"}\":{\"c\":{\"d\":\"d\",\"e\":\"e\"}}}"

But when I parse the data, the first key is not parsed:

JSON.parse data_json

# => {"{:a=>\"a\", :b=>\"b\"}"=>{"c"=>{"d"=>"d", "e"=>"e"}}}

Why JSON.parse acts like that? and How can I fix it ?

1

There are 1 best solutions below

0
On

In your original data structure, you have a Hash containing a single key-value pair. However, the key for this pair is itself a hash. This is not allowed in JSON (as only string keys are allowed in JSON), resulting in Ruby's JSON library to trying to do something sensible here: it inspects the key and uses the resulting String as the key in the created JSON object.

Unfortunately, this operation is not reversible when parsing the JSON object again. To solve this, You should try to adapt your source data structure to match what is allowed in JSON, i.e. to only use String keys in your hashes.