本文主要是介绍[解决办法]Python中使用json.loads解码字符串时出错:ValueError: Expecting property name: line 1 column 2 (char 1),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述
今天在解析字符串中,使用json.loads解码字符串,脚本如下:
import json
string = "{u'lat': 61.190495, u'lng': -149.86884}"
dic = json.loads(string)
运行后报错信息如下:
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/usr/lib64/python2.6/json/__init__.py", line 307, in loadsreturn _default_decoder.decode(s)File "/usr/lib64/python2.6/json/decoder.py", line 319, in decodeobj, end = self.raw_decode(s, idx=_w(s, 0).end())File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decodeobj, end = self._scanner.iterscan(s, **kw).next()File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscanrval, next_pos = action(m, context)File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObjectraise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 1 (char 1)
解决方案
1. 替换单引号
类型的错误,就是由于JSON中,标准语法中,不支持单引号,属性或者属性值,都必须是双引号括起来的。
string = string.replace("'", '"')
dic = json.loads(string)
依旧报同样的错误信息,如下:
Traceback (most recent call last):File "<stdin>", line 1, in <module>File "/usr/lib64/python2.6/json/__init__.py", line 307, in loadsreturn _default_decoder.decode(s)File "/usr/lib64/python2.6/json/decoder.py", line 319, in decodeobj, end = self.raw_decode(s, idx=_w(s, 0).end())File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decodeobj, end = self._scanner.iterscan(s, **kw).next()File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscanrval, next_pos = action(m, context)File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObjectraise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 1 (char 1)
2. 替换引号前的u
为空,
即去除引号前的u
。这种解决编码问题,简单粗暴了点,至于其深入分析,未完待绪。同时也希望各位大神能够提供更好的解决办法。
string = string.replace("u", "") # 这里比较简单,实际中需要用正则条件替换
dic = json.loads(string)
更多参考
http://www.tuicool.com/articles/YBnE3q
http://www.chenxm.cc/post/328.html?csdn
这篇关于[解决办法]Python中使用json.loads解码字符串时出错:ValueError: Expecting property name: line 1 column 2 (char 1)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!