使用Python编码、解码JSON对象

测试版本为Python2.7

import json

pObj = {
    "int":10,
    "string":"test",
    "true":True,
    "false":False,
    "null":None,
    "list":["a"],
    "tuple":("a",)
    }
print "type=%s content=%s"%(type(pObj), pObj)
jsonStr = json.dumps(pObj) #编码
print "type=%s content=%s"%(type(jsonStr), jsonStr)
obj= json.loads(jsonStr) #解码
print "type=%s content=%s"%(type(obj), obj)

执行结果如下:

type=<type 'dict'> content={'false': False, 'string': 'test', 'tuple': ('a',), 'int': 10, 'list': ['a'], 'null': None, 'true': True}
type=<type 'str'> content={"false": false, "string": "test", "tuple": ["a"], "int": 10, "list": ["a"], "null": null, "true": true}
type=<type 'dict'> content={u'false': False, u'string': u'test', u'tuple': [u'a'], u'int': 10, u'list': [u'a'], u'null': None, u'true': True}

参考Python源码中的注释,编码结果如下图

+-------------------+---------------+
| Python            | JSON          |
+===================+===============+
| dict              | object        |
+-------------------+---------------+
| list, tuple       | array         |
+-------------------+---------------+
| str, unicode      | string        |
+-------------------+---------------+
| int, long, float  | number        |
+-------------------+---------------+
| True              | true          |
+-------------------+---------------+
| False             | false         |
+-------------------+---------------+
| None              | null          |
+-------------------+---------------+

解码结果如下图:

+---------------+-------------------+
| JSON          | Python            |
+===============+===================+
| object        | dict              |
+---------------+-------------------+
| array         | list              |
+---------------+-------------------+
| string        | unicode           |
+---------------+-------------------+
| number (int)  | int, long         |
+---------------+-------------------+
| number (real) | float             |
+---------------+-------------------+
| true          | True              |
+---------------+-------------------+
| false         | False             |
+---------------+-------------------+
| null          | None              |
+---------------+-------------------+

在解码的过程中遇到了一些问题:

import json

a = '{"name":"sean"}'
#b = '{'''name''':'''sean'''}' 编译异常
c = "{'name':'sean'}"
d = "{'''name''':'''sean'''}"
e = '''{'name':'sean'}'''
f = '''{"name":"sean"}'''
g = "{\"name\":\"sean\"}"

obj = json.loads(g)
print "type=%s content=%s" % (type(obj), obj)

debug结果如图


无论最外层使用单引号、双引号还是三引号,解析器解析后都会变为单引号,只要内外层引号不重复即可,否则内层引号前将添加\\导致解析错误


猜你喜欢

转载自blog.csdn.net/a19881029/article/details/79392786
今日推荐