使用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

其执行输出如下:

[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"}

后面的结构体转义部分,实际上就是json.JSONEncoder().encode方法处理的结果:

print json.JSONEncoder().encode(cmd)

可以用上面的命令进行测试,将上面的代码加入到上面python文件的最后,执行的结果如下:

[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"

原文来自:http://www.361way.com/python-class-tojson/5865.html

本文地址:https://www.linuxprobe.com/python-sorrt-json.html编辑:问题终结者,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/