我正在尝试使用json.loads()将以下字符串转换为json:
targetingConditions = "[{\"filters\":[{\"key\":\"domain\",\"rel\":\"neq\",\"values\":['science.howstuffworks.com', 'conduit.com', 'usatoday.com']}]}]"
我知道反斜杠可能会导致问题,就像我在类似的问题和答案中看到的那样。我试图用这样的双反斜杠替换反斜杠:
targetingConditions.replace('\\', '\\\\')
以及我在类似问题的答案中找到的任何其他可想象的选项或示例。
代码是:
json.loads(targetingConditions)
我得到的输出:
Traceback (most recent call last):
File "C:/Users/uesr/Google Drive/SHARED/Automation project/Automations/streamrail/tests.py", line 36, in <module>
tag_filters = json.loads(tag_filters)
File "C:\Users\uesr\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\uesr\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\uesr\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 52 (char 51)
答案 0 :(得分:1)
你的字符串不是有效的JSON。 JSON只接受双引号,因此您需要替换targetingConditions
中的单引号
targetingConditions = '[{"filters":[{"key":"domain","rel":"neq","values":["science.howstuffworks.com", "conduit.com", "usatoday.com"]}]}]'
这允许你用单引号包装所有内容,这意味着你不必逃避任何事情。然后,您可以使用json.loads
将其设为python对象,或者直接将其写入文件。您可能会发现JSON specification将来有用,或者使用预先构建的JSON validator
答案 1 :(得分:0)
我相信你的json字符串很糟糕,因为我试图用JavaScript解析它并给了我这个错误
Uncaught SyntaxError: Unexpected token ' in JSON at position 51
at JSON.parse (<anonymous>)
at <anonymous>:1:6
但是如果你将字符串改为
"[{\"filters\":[{\"key\":\"domain\",\"rel\":\"neq\",\"values\":[\"science.howstuffworks.com\", \"conduit.com\", \"usatoday.com\"]}]}]"
现在可以使用,因为JSON的字符串用双引号而不是单引号括起来。单引号是在python中表示字符串的可能方式,但对于JSON,双引号中的唯一方法。
此外,您不需要将\替换为\,因为\“表示双引号。