使用 python 从命令行传递的 json 参数无法解码

json argument passed from the command line with python can't be decoded

我正在尝试将命令行参数传递给 python 文件并加载 json 但是 我不断收到值错误:无法解码 Json 对象。

json_test.py:

import json
import sys

json_dict = json.loads(sys.argv[1])

然后我 运行 在命令行中使用:

python json_test.py '{"favorited": false, "contributors": null}'

我收到一个错误,尽管我在网络上发现这是正确 JSON 的示例。有什么想法吗?

如果你 运行 print sys.argv[1] 你可能会得到 '{favorited: json 模块无法解码成 json 对象。

尝试转义您的内部引号,以便将其作为 1 个参数传递,如下所示:

"{"\""favorited"\"": false, "\""contributors"\"": null}"