将Ruby哈希字符串转换为Python字典 [英] Converting a Ruby hash string to a Python dictionary

查看:55
本文介绍了将Ruby哈希字符串转换为Python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一些命令输出,这些命令作为Ruby哈希的字符串返回.(摘自mcollective).

I'm working with some command output that's returned as the string of a Ruby hash. (From something called mcollective).

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

Here is an example string I'm receiving:

{: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字典的库或代码片段?

I'm capable of writing a mini parser for this, but it would be a fiddly task. Does anyone know of a library or code snippet that could convert this for me into a Python dictionary?

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

If you think I should just parse it, any tips are welcome.

推荐答案

实际上,编写足以满足我的需求的东西还不错.不是最漂亮的东西,但是对我有用.

Actually it wasn't too bad to write something good enough for my needs. Not the prettiest thing, but it will do for me.

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

这篇关于将Ruby哈希字符串转换为Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆