python处理字典中双引号_2.3. 字典类型的json字符串中的key要用双引号,而不能用单引号...

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,必须是用双引号括起来的,不能少了双引号,也不能是单引号,只能是双引号。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值