Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a Ruby hash string to a Python dictionary

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

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.

like image 841
joeButler Avatar asked Oct 11 '13 13:10

joeButler


2 Answers

You can easily convert it to JSON using the following command:

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

Then use Python's JSON library to parse it.

like image 54
Slicedpan Avatar answered Sep 22 '22 14:09

Slicedpan


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) 
like image 45
joeButler Avatar answered Sep 23 '22 14:09

joeButler