【发布时间】:2015-04-12 10:39:08
【问题描述】:
在 python 脚本中,我正在解析返回的gsettings get org.gnome.system.proxy ignore-hosts
看起来应该正确格式化JSON['localhost', '127.0.0.0/8']
但是,当将此输出传递给 json.loads 时,它会抛出ValueError: No JSON object could be decoded
我通过以下方式调用 gsettings:
import subprocess
proc = subprocess.Popen(["gsettings", "get", "org.gnome.system.proxy", "ignore-hosts"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout,stderr = proc.communicate()
将"['localhost', '127.0.0.0/8']\n" 分配给stdout。
然后我去掉换行符并传递给 json.loads:
ignore = json.loads(stdout.strip("\n"))
但是,这会引发ValueError。
我已将问题追溯到由单引号或双引号定义的字符串,如下面的 sn-p 所示:
# tested in python 2.7.3
import json
ignore_hosts_works = '["localhost", "127.0.0.0/8"]'
ignore_hosts_fails = "['localhost', '127.0.0.0/8']"
json.loads(ignore_hosts_works) # produces list of unicode strings
json.loads(ignore_hosts_fails) # ValueError: No JSON object could be decoded
import string
table = string.maketrans("\"'", "'\"")
json.loads(string.translate(ignore_hosts_fails, table)) # produces list of unicode strings
为什么json.loads 没有在不交换引号类型的情况下成功解析ignore_hosts_fails?
以防万一,我正在运行带有 Python 2.7.3 的 Ubuntu 12.04。
【问题讨论】:
-
['localhost', '127.0.0.0/8']的 JSON 格式不正确。 JSON 要求使用 双 引号。见chapter 7 of the RFC,quotation-mark定义为"。 -
啊,谢谢。 双引号要求在阅读json.org时对我来说并不突出。
标签: python json string python-2.7