Python解析json时提示“string indices must be integers”问题解决方法
本文实例讲述了Python解析json时提示“stringindicesmustbeintegers"问题解决方法。分享给大家供大家参考,具体如下:
importjson,但是出现了一个奇怪的问题:
stringindicesmustbeintegers
这个错误告诉我,[]里面应该是数字而不是字符串,但是dict使用key访问也可以,这种错误感觉解析出来的结果像是一个list。
所以考虑是字符串解析的问题。打印解析的结果,是一长串的字符串,一堆的key挤在一起,value都缺失了。再打印原始的字符串,发现了一些细节,key并没有被双引号包围,类似于'{a:"abcde",b:"abcde"}'。
好吧,这是一个不符合json规范的字符串,要处理它,可以使用正则表达式转换成规范的key再解析或者使用其他功能更加强大的库——demjson。
pipinstalldemjson,解决。
json的用法:
importjson data=[{'a':1,'b':2,'c':3,'d':4,'e':5}] json=json.dumps(data) printjson
结果为:
[{"a":1,"c":3,"b":2,"e":5,"d":4}]
importjson jsonData='{"a":1,"b":2,"c":3,"d":4,"e":5}'; text=json.loads(jsonData) printtext
结果为:
{u'a':1,u'c':3,u'b':2,u'e':5,u'd':4}
demjson的用法:
importdemjson data=[{'a':1,'b':2,'c':3,'d':4,'e':5}] json=demjson.encode(data) printjson
结果为:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
importdemjson json='{"a":1,"b":2,"c":3,"d":4,"e":5}'; text=demjson.decode(json) printtext
结果为:
{u'a':1,u'c':3,u'b':2,u'e':5,u'd':4}
importdemjson data=[{'a':1,'b':2,'c':3,'d':4,'e':5}] json=demjson.encode(data) printjson
结果为:
[{"a":1,"b":2,"c":3,"d":4,"e":5}]
importdemjson json='{"a":1,"b":2,"c":3,"d":4,"e":5}'; text=demjson.decode(json) printtext
结果为:
{u'a':1,u'c':3,u'b':2,u'e':5,u'd':4}
PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/