2013-10-11 113 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

相關問題