我有一個轉換為 YAML 的物件,但它沒有給我想要的結果。
我得到的結果
---
accepted:
first_order_date:
consition: between_date
value: 2021-11-28 00:00:00&2021-11-22 00:00:00
removed: {}
我想要的結果
--- !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 {}
這是我的代碼
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
我是 ruby?? 的新手,所以請幫助找出我該怎么做。
uj5u.com熱心網友回復:
正如你想要的結果HashWithIndifferentAccess你可以做到這一點之前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
輸出:
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
參考:hash_with_indifferent_access 官方
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358264.html
標籤:红宝石
下一篇:Rails服務器在起點出現錯誤
