2013-10-11 114 views
5

我正在处理一些作为Ruby哈希字符串返回的命令输出。 (来自所谓的mcollective)。将Ruby哈希字符串转换为Python字典

这是我收到的示例串:

{: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}} 

我能够写这个小解析器,但是这将是一个繁琐的任务。有没有人知道一个库或代码片段,可以将它转换成Python字典?

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

+1

一个简单的黑客就是用= 1替换=:[a-z] +,然后调用ast.literal_eval或json.loads。这是不正确的,因为它忽略了字符串文字,但现在可能已经足够好了。 – Antimony

+0

根据他们的文档http://docs.puppetlabs.com/mcollective/reference/basic/basic_cli_usage.html他们也可以导出JSON:'-j'标志。 – georg

+0

不幸的是,版本即时运行。但是,这将是最好的 – joeButler

回答

4

事实上,写出足够满足我需求的东西并不算太坏。不是最漂亮的东西,但它会为我做。

# 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) 
3

你有没有考虑过使用Ruby来将其序列化为JSON?这样你可以用Python的JSON库对它进行反序列化。

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

然后:https://pypi.python.org/pypi/Parsley

6

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

如果这不是一种选择,你可以使用这个库定义相对容易定制的结构化语言解析器使用Python的JSON库来解析它。

+0

了解更多信息。这是一种可能性, - 它确实需要我确保系统上有一个ruby解释器,但并非总是如此。 – joeButler

相关问题