2.3. 字典类型的json字符串中的key要用双引号,而不能用单引号
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]}}
dict类型json字符串中的key,如果用单引号,是不行的
另外,也去尝试过了,把双引号都替换为单引号:
timeFillingInfoJson = timeFillingInfoJson.replace('"', "'");
timeFillingInfoDict = json.loads(timeFillingInfoJson);
logging.info("timeFillingInfoDict=%s", timeFillingInfoDict);
结果同样会出错的:
ValueError: Expecting property name: line 1 column 1 (char 1)
所以,看来dict的json字符串中的key,必须是用双引号括起来的,不能少了双引号,也不能是单引号,只能是双引号。