您好,登錄后才能下訂單哦!
這篇“python序列化json數(shù)據(jù)的方法是什么”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來(lái)看看這篇“python序列化json數(shù)據(jù)的方法是什么”文章吧。
使用json模塊提供的loads方法和dumps方法,可以很方便的載入和讀取json數(shù)據(jù)格式。
可以借用python內(nèi)部的dict 字典方法將格式轉(zhuǎn)換為json格式并讀取,不帶參數(shù)示例如下:
class Foo(object): def __init__(self): self.x = 1 self.y = 2 foo = Foo()# s = json.dumps(foo) # raises TypeError with "is not JSON serializable"s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}
調(diào)用上面的方法時(shí),print s時(shí),其值為:{“x”:1, “y”:2} 。
如果要傳入的是一個(gè)多行字符串參數(shù),其也可以自動(dòng)進(jìn)行轉(zhuǎn)義:
#!/usr/bin/env python# coding=utf8# Copyright (C) 2018 www.361way.com site All rights reserved.import json class Foo(object): def __init__(self,cmd): self.Command = cmd cmd=""" #!/bin/bash echo "Result:4 " ps -ef|grep java|wc -l netstat -an|grep 15380 echo ";" """foo = Foo(cmd) s = json.dumps(foo.__dict__)print s
其執(zhí)行輸出如下:
[root@localhost tmp]# python a.py{"Command": "\n#!/bin/bash\n\necho \"Result:4 \"\nps -ef|grep java|wc -l\nnetstat -an|grep 15380\necho \";\"\n\n"}
后面的結(jié)構(gòu)體轉(zhuǎn)義部分,實(shí)際上就是json.JSONEncoder().encode方法處理的結(jié)果:
print json.JSONEncoder().encode(cmd)
可以用上面的命令進(jìn)行測(cè)試,將上面的代碼加入到上面python文件的最后,執(zhí)行的結(jié)果如下:
[root@localhost tmp]# python a.py{"Command": "\n#!/bin/bash\n\necho \"Result:4 \"\nps -ef|grep java|wc -l\nnetstat -an|grep 15380\necho \";\"\n\n"}"\n#!/bin/bash\n\necho \"Result:4 \"\nps -ef|grep java|wc -l\nnetstat -an|grep 15380\necho \";\"\n\n"
以上就是關(guān)于“python序列化json數(shù)據(jù)的方法是什么”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。