2013-04-07 31 views
26

私はPython:有効なUUIDをStringからUUIDに変換する方法は?

{ 
     "name": "Unknown", 
     "parent": "Uncategorized", 
     "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16" 
    }, 

などのデータを受信して​​、私はpython docsの道を見つけられませんでした私は、uuid

Stringからuuidを変換する必要がある、または私はここで基本的な何かが足りないのですか?

+0

あなたがチェックアウトすることをお勧めします[この他の質問/答え](http://stackoverflow.com/questions/534839/how-to-create-a-guid-in-python?rq=1) [こちらのドキュメント](http://docs.python.org/2/library/uuid.html)も参照してください。 :) – summea

答えて

41

だけuuid.UUIDに渡し:

import uuid 

o = { 
    "name": "Unknown", 
    "parent": "Uncategorized", 
    "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16" 
} 

print uuid.UUID(o['uuid']).hex 
0

を上記の答えはuuid.UUID(your_uuid_string)が私のために働いて使用して...実際のUUIDオブジェクトに戻って文字列形式で有効なUUIDを変換するためのあなたのために動作しなかった場合。

In [6]: import uuid 
    ...: 
    ...: o = { 
    ...:  "name": "Unknown", 
    ...:  "parent": "Uncategorized", 
    ...:  "uuid": "06335e84-2872-4914-8c5d-3ed07d2a2f16" 
    ...: } 
    ...: 
    ...: print uuid.UUID(o['uuid']).hex 
    ...: print type(uuid.UUID(o['uuid']).hex) 
06335e84287249148c5d3ed07d2a2f16 
<type 'str'> 

In [7]: your_uuid_string = uuid.UUID(o['uuid']).hex 

In [8]: print uuid.UUID(your_uuid_string) 
06335e84-2872-4914-8c5d-3ed07d2a2f16 

In [9]: print type(uuid.UUID(your_uuid_string)) 
<class 'uuid.UUID'> 
関連する問題