将Ruby哈希字符串转换为Python字典

joe*_*ler 5 ruby python parsing dictionary hashmap

我正在使用一些命令输出,它作为Ruby哈希的字符串返回.(来自mcollective的东西).

这是我收到的示例字符串:

{:changes=>{"total"=>0},     :events=>{"failure"=>0, "success"=>0, "total"=>0},     :version=>      {"puppet"=>"2.7.21 (Puppet Enterprise 2.8.1)", "config"=>1381497648},     :time=>      {"filebucket"=>0.000287,       "cron"=>0.00212,       "package"=>0.398982,       "exec"=>0.001314,       "config_retrieval"=>5.60761618614197,       "anchor"=>0.001157,       "service"=>0.774906,       "total"=>9.85111718614197,       "host"=>0.002662,       "user"=>0.063606,       "file"=>2.998467,       "last_run"=>1381497660},     :resources=>      {"skipped"=>6,       "failed_to_restart"=>0,       "out_of_sync"=>0,       "failed"=>0,       "total"=>112,       "restarted"=>0,       "scheduled"=>0,       "changed"=>0}}
Run Code Online (Sandbox Code Playgroud)

我有能力为此编写一个迷你解析器,但这将是一个繁琐的任务.有谁知道一个库或代码片段可以将我转换为Python字典?

如果您认为我应该解析它,欢迎任何提示.

Sli*_*pan 6

您可以使用以下命令轻松将其转换为JSON:

ruby -e 'require "json"; puts JSON.generate({:ruby_hash => "whatever etc..."})'
Run Code Online (Sandbox Code Playgroud)

然后使用Python的JSON库来解析它.


joe*_*ler 5

实际上,写一些足以满足我需求的东西并不算太糟糕.不是最漂亮的东西,但它会为我做.

# Sometimes MCO gives us a ruby hash as a string, We can coerce this into json then into dictionary
def convert_hash_to_dict(self,ruby_hash):
    dict_str = ruby_hash.replace(":",'"')    # Remove the ruby object key prefix
    dict_str = dict_str.replace("=>",'" : ') # swap the k => v notation, and close any unshut quotes 
    dict_str = dict_str.replace('""','"')    # strip back any double quotes we created to sinlges
    return json.loads(dict_str) 
Run Code Online (Sandbox Code Playgroud)