我有一個數組來存儲一些這樣的數據,這是我正在使用的確切輸入
{
"accepted" => {
"number_of_order" => {
"condition" => "between_number", "value" => "0&5"
}
}, "removed" => {
}
}
現在我正在嘗試將此數組轉換為這樣的 ruby 哈希訪問,這是我的預期輸出,這不是我現在得到的
--- !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 {}
但我無法在 ruby 哈希訪問中轉換數組。我還嘗試將 YAML 轉儲Yaml::dump($array);
轉換為 YAML,然後使用 ruby 哈希訪問,但沒有任何效果。
基本上,我試圖扭轉這個問題
如何從 ruby 哈希訪問 Laravel 8 獲取數據?
您可以參考上面的鏈接,我將此 ruby 哈希轉換為 laravel 數組,但現在我也想將此數組轉換為 ruby 哈希。
我當前用於將數組轉換為 ruby 哈希的代碼
$jsonEncoded = '{"accepted":{"number_of_order":{"consition":"between_number","value":"0&5"}}}';
$array = json_decode($jsonEncoded, true);
dump(Yaml::dump($array));
我當前用於將 ruby 哈希轉換為數組的代碼
$filter_data = str_replace("!ruby/hash:ActiveSupport::HashWithIndifferentAccess", "", $filter_data);
$yamlContents = Yaml::parse($filter_data);
我剛剛找到了我的問題的答案,並與大家分享。
Laravel 代碼:
$jsonEncoded = '{"accepted":{"first_order_number":{"consition":"between_date","value":"2021-11-28 00:00:00&2021-11-22 00:00:00"}},"removed":{}}';
$process = new Process(['ruby', 'convert_hashActiveSupport.rb'],null,null, $jsonEncoded);
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
$data = $process->getOutput();
紅寶石代碼:
require 'yaml'
require 'json'
require "active_support/core_ext/hash/indifferent_access"
yaml_str = "#{ ARGF.read }"
parsed_output = JSON.parse(yaml_str)
yaml_output = parsed_output.with_indifferent_access.to_yaml
puts yaml_output
laravel 中需要的包:
composer require symfony/process
ruby 中需要的包:
gem install activesupport
gem install '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 {}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句