[解决办法]Python中使用json.loads解码字符串时出错:ValueError: Expecting property name: line 1 column 2 (char 1)

时间:2022-05-17 17:05:15

原文:http://blog.csdn.net/sinsa110/article/details/51189456

问题描述

今天在解析字符串中,使用json.loads解码字符串,脚本如下:

import json
string = "{u'lat': 61.190495, u'lng': -149.86884}"
dic = json.loads(string)
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

运行后报错信息如下:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode
obj, end = self._scanner.iterscan(s, **kw).next()
File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObject
raise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 1 (char 1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

解决方案

1. 替换单引号

类型的错误,就是由于JSON中,标准语法中,不支持单引号,属性或者属性值,都必须是双引号括起来的。

string = string.replace("'", '"')
dic = json.loads(string)
  • 1
  • 2
  • 1
  • 2

依旧报同样的错误信息,如下:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads
return _default_decoder.decode(s)
File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib64/python2.6/json/decoder.py", line 336, in raw_decode
obj, end = self._scanner.iterscan(s, **kw).next()
File "/usr/lib64/python2.6/json/scanner.py", line 55, in iterscan
rval, next_pos = action(m, context)
File "/usr/lib64/python2.6/json/decoder.py", line 171, in JSONObject
raise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 1 (char 1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2. 替换引号前的u为空,

即去除引号前的u。这种解决编码问题,简单粗暴了点,至于其深入分析,未完待绪。同时也希望各位大神能够提供更好的解决办法。

string = string.replace("u", "") # 这里比较简单,实际中需要用正则条件替换
dic = json.loads(string)