I have an object that I converted to YAML but it's not giving me the same result which I want.
The result I got
---
accepted:
first_order_date:
consition: between_date
value: 2021-11-28 00:00:00&2021-11-22 00:00:00
removed: {}
The result I want
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
accepted: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
number_of_order: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
condition: between_number
value: 0&5
removed: !ruby/hash:ActiveSupport::HashWithIndifferentAccess {}
And here is my code
require 'yaml'
require 'json'
yaml_str = '{"accepted":{"first_order_date":{"consition":"between_date","value":"2021-11-28 00:00:00&2021-11-22 00:00:00"}},"removed":{}}'
puts JSON.parse(yaml_str).to_yaml
I'm new at ruby so please help to find out how can i do this.
CodePudding user response:
As you want result with HashWithIndifferentAccess
You can do this before to_yaml
require 'yaml'
require 'json'
yaml_str = '{"accepted":{"first_order_date":{"consition":"between_date","value":"2021-11-28 00:00:00&2021-11-22 00:00:00"}},"removed":{}}'
parsed_output = JSON.parse(yaml_str)
yaml_output = parsed_output.with_indifferent_access.to_yaml
puts yaml_output
Output:
puts JSON.parse(yaml_str).with_indifferent_access.to_yaml
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess
accepted: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
first_order_date: !ruby/hash:ActiveSupport::HashWithIndifferentAccess
consition: between_date
value: 2021-11-28 00:00:00&2021-11-22 00:00:00
removed: !ruby/hash:ActiveSupport::HashWithIndifferentAccess {}
=> nil
Ref: hash_with_indifferent_access offcial
Cheers