1. 程式人生 > >python如何序列化json資料

python如何序列化json資料

 使用json模組提供的loads方法和dumps方法,可以很方便的載入和讀取json資料格式。而在具體實際應用中,我們使用python資料格式是 string、list 或dict等,這類格式如何直接轉換為json格式呢?

可以借用python內部的__dict__ 字典方法將格式轉換為json格式並讀取,不帶引數示例如下:

一、不帶引數的class類轉化為json

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}

呼叫上面的方法時,print s時,其值為:{"x":1, "y":2} 。

二、帶引數的class方法轉化為json

如果要傳入的是一個多行字串引數,其也可以自動進行轉義:

#!/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

其執行輸出如下:

[[email protected] 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"}

後面的結構體轉義部分,實際上就是json.JSONEncoder().encode方法處理的結果:

print json.JSONEncoder().encode(cmd)

可以用上面的命令進行測試,將上面的程式碼加入到上面python檔案的最後,執行的結果如下:

[[email protected] 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"