python:无法将字符串转换为json

时间:2019-03-14 18:04:20

标签: python json

尽管以下内容似乎是有效的json字符串,但我无法json.load

In [33]:  mystr="{ 'username': 'Newman Test Executor', 'channel': '#someslackchannel' }"

In [34]: json.loads(mystr)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-34-6f4efa0d20c6> in <module>()
----> 1 json.loads(mystr)

/usr/lib/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    337             parse_int is None and parse_float is None and
    338             parse_constant is None and object_pairs_hook is None and not kw):
--> 339         return _default_decoder.decode(s)
    340     if cls is None:
    341         cls = JSONDecoder

/usr/lib/python2.7/json/decoder.pyc in decode(self, s, _w)
    362 
    363         """
--> 364         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    365         end = _w(s, end).end()
    366         if end != len(s):

/usr/lib/python2.7/json/decoder.pyc in raw_decode(self, s, idx)
    378         """
    379         try:
--> 380             obj, end = self.scan_once(s, idx)
    381         except StopIteration:
    382             raise ValueError("No JSON object could be decoded")

ValueError: Expecting property name: line 1 column 3 (char 2)

4 个答案:

答案 0 :(得分:2)

就像上面提到的@Austin和@Arya一样,您需要在JSON字符串中使用双引号将其有效。就您而言,您可以简单地将单引号替换为双引号:

import json
mystr="{ 'username': 'Newman Test Executor', 'channel': '#someslackchannel' }"
json.loads(mystr.replace('\'','"'))

答案 1 :(得分:2)

import json
mystr = '{ "username": "Newman Test Executor", "channel": "#someslackchannel" }'
my_dict = { "username": "Newman Test Executor", "channel": "#someslackchannel" }



print(json.loads(mystr))
print(json.dumps(my_dict))

输出:

{u'username': u'Newman Test Executor', u'channel': u'#someslackchannel'}
{"username": "Newman Test Executor", "channel": "#someslackchannel"}

在单引号外,在双引号内则是字符串。

如果您无法控制传递给您的json string,则可以使用 Vasilis G。

中提到的mystr.replace('\'', '"')

答案 2 :(得分:0)

您需要在JSON字符串中加双引号。

请参见Parsing string as JSON with single quotes?

  

JSON标准要求双引号,并且不接受单引号,解析器也将不接受。

答案 3 :(得分:0)

遵循Arya的评论,并使代码生效。答案可以在其他论坛找到。

import json
mystr='{ "username": "Newman Test Executor","channel": "#someslackchannel"}'

json.loads(mystr)