您的位置:首页 > 编程语言 > Python开发

使用Python编码、解码JSON对象

2018-02-27 20:37 411 查看
测试版本为Python2.7import 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结果如图



无论最外层使用单引号、双引号还是三引号,解析器解析后都会变为单引号,只要内外层引号不重复即可,否则内层引号前将添加\\导致解析错误
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐