版本:v1.1
摘要
本文主要介绍了JSON的基础知识,以及在具体(Python,C#等)编程语言中,如何处理JSON,以及常见错误和解决办法。
2013-09-05
修订历史 | ||
---|---|---|
修订 1.1 | 2013-09-05 | crl |
|
版权 © 2013 Crifan, http://crifan.com
目录
Python中,有专门的JSON处理模块,名字就叫做:json
如果json字符串的内容中包含单引号或双引号,直接用json.loads去转换的话,则会导致出错。
解决办法是,把所含的(用双引号括起来的)内容中单引号或双引号前,加上反斜杠即可。
以双引号为例,即,从
"key":"value incldue " "
变为
"key":"value incldue \" "
json字符串是字典变量类型的字符串的时候,对应字典中的key部分,是需要用双引号括起来的,否则json.loads会出错的。
详情参看:【已解决】Python中用json.loads去解析字符串出错:ValueError: Expecting property name: line 1 column 51 (char 51)
json字符串是字典变量类型的字符串的时候,对应字典中的key部分,注意是用双引号括起来,而不能是单引号,否则也是会导致json.loads出错的。
比如对于字符串变量timeFillingInfoJson:
{'2012' : {"month" : [0,0,0,0,0,0,0,-1,-1,-1,-1,-1],"totalCount" : '0'},'2011' : {"month" : [0,0,0,0,0,0,0,0,0,0,0,0],"totalCount" : '0'},'2010' : {"month" : [5,21,22,20,11,7,8,11,12,0,0,1],"totalCount" : '118'},'2009' : {"month" : [0,13,9,20,63,32,35,32,24,39,15,6],"totalCount" : '288'},'2008' : {"month" : [6,40,83,66,35,35,11,5,3,4,0,1],"totalCount" : '289'},'2007' : {"month" : [-1,-1,-1,6,0,19,10,8,3,41,47,44],"totalCount" : '178'}}
用代码:
timeFillingInfoDict = json.loads(timeFillingInfoJson); logging.info("timeFillingInfoDict=%s", timeFillingInfoDict);
去解析会出错:
ValueError: Expecting property name: line 1 column 1 (char 1)
而把单引号替换为双引号后:
{"2012" : {"month" : [0,0,0,0,0,0,0,-1,-1,-1,-1,-1],"totalCount" : "0"},"2011" : {"month" : [0,0,0,0,0,0,0,0,0,0,0,0],"totalCount" : "0"},"2010" : {"month" : [5,21,22,20,11,7,8,11,12,0,0,1],"totalCount" : "118"},"2009" : {"month" : [0,13,9,20,63,32,35,32,24,39,15,6],"totalCount" : "288"},"2008" : {"month" : [6,40,83,66,35,35,11,5,3,4,0,1],"totalCount" : "289"},"2007" : {"month" : [-1,-1,-1,6,0,19,10,8,3,41,47,44],"totalCount" : "178"}}
就可以正常解析,得到对应的dict变量了:
timeFillingInfoDict={u'2007': {u'totalCount': u'178', u'month': [-1, -1, -1, 6, 0, 19, 10, 8, 3, 41, 47, 44]}, u'2008': {u'totalCount': u'289', u'month': [6, 40, 83, 66, 35, 35, 11, 5, 3, 4, 0, 1]}, u'2009': {u'totalCount': u'288', u'month': [0, 13, 9, 20, 63, 32, 35, 32, 24, 39, 15, 6]}, u'2011': {u'totalCount': u'0', u'month': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}, u'2010': {u'totalCount': u'118', u'month': [5, 21, 22, 20, 11, 7, 8, 11, 12, 0, 0, 1]}, u'2012': {u'totalCount': u'0', u'month': [0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1]}}
[1] python初级教程:入门详解