當前位置:成語大全網 - 英語詞典 - 如何用python將protobuf轉換成json

如何用python將protobuf轉換成json

直接使用python提供的json包,在django模型的定義中添加壹個方法toJSON,使用django模型訪問_meta.fields得到相關屬性。示例如下:

類別類別(型號。型號):

autoid =型號。AutoField(primary_key=True)

郵件=模特。CharField(max_length=150,blank=False)

comtype =模型。CharField(max_length=20,blank=False)

catname =模型。CharField(max_length=150,blank=False)

def __unicode__(self):

返回“% s”%(self . cat name)

def toJSON(self):

導入json

返回JSON . dumps(dict((attr,getattr(self,attr))for attr in[f . name for f in self ._meta.fields]]))

然後用django找出數據,轉換成json。代碼如下:

row =模型。Category.objects.get(autoid=23)

打印row.toJSON()