使用空格传递 Python JSON 参数

Passing Python JSON argument with whitespace

我正在尝试将 JSON 作为参数传递给命令提示符中的 python 脚本。如果 JSON 中的元素值中没有空格,它会起作用,但如果有空格,它就不起作用。

这是脚本

import json, sys, traceback
    if(len(sys.argv)>1):
    print(sys.argv[1])
    jsonInput = json.loads(sys.argv[1]);
    print(jsonInput['name'])
    print(jsonInput['kingdom'])
    print(jsonInput['slogan'])

在 JSON 下方作为幂 Shell 中的参数传递。我在值中有空格,例如琼恩·雪诺

python C:\Users\user1\Desktop\myTest.py '{\"name\":\"Jon Snow\",\"kingdom\":\"Winterfell\",\"slogan\":\"King in the North\"}'

输出:

python : Traceback (most recent call last):
At line:1 char:1
+ python C:\Users\kiran.patil\Desktop\myTest.py '{\"name\":\"Jon Snow\" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Traceback (most recent call last)::String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
  File "C:\Users\User\Desktop\myTest.py", line 5, in <module>
    jsonInput = json.loads(sys.argv[1]);
  File "C:\Program Files\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\Python38\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 9 (char 8)

请任何修复它的建议。

如果您使用 \",则表示括起来的引号也是双引号。在 windows 上,封闭的单引号不起作用,因此 2 个选项是

# Linux + Windows
python script.py "{\"name\":\"Jon Snow\",\"kingdom\":\"Winterfell\",\"slogan\":\"King in theNorth\"}"

# Linux only
python script.py '{"name":"Jon Snow","kingdom":"Winterfell","slogan":"King in theNorth"}'

Powershell 案例

python script.py '{""name"":""Jon Snow"",""kingdom"":""Winterfell"",""slogan"":""King in theNorth""}'

PowerShell中:

  • 您的尝试事实上没有根本错误将嵌入的 " 字符转义为 \" 以调用 外部程序 (例如 Python),尽管它们被包含在引号字符串 ('...'):

    • 由于 Windows PowerShell 中的 附加 错误(除了讨论的基本错误之外下面),此后已在 PowerShell [Core] v6+ 中修复,具有 \" 转义的字符串仅在包含 至少一个 space 字符.

    • 换句话说:在 PowerShell [Core] v6+ 中,您的命令 会起作用 as-is ;在 Windows PowerShell 中,它 仅当您的字符串包含 至少一个 space 字符 时才有效.

    • 因为在这个特定的上下文中(仅!)\""" 可互换的 "" 的使用也适用于 Windows PowerShell 中的 space-less 字符串,""-escaping,如中所示,是比较稳健的选择; 警告 大多数,但不是全部 Windows 上的 CLI 将 "" 识别为转义的 "字符,而那些不识别 \".

# OK even in Windows PowerShell, due to the string containing spaces.
# "" instead of \" works too and avoids the need for spaces in Windows PowerShell
#  - but neither should be necessary (see below).
python myTest.py '{\"name\": \"Jon Snow\", \"kingdom\": \"Winterfell\", \"slogan\": \"King in the North\"}'
  • 应该有问题,但是,因为你不必转义 " 个字符。在 '...' 分隔的字符串文字 中,它是 verbatim string literal in PowerShell.

    • 事实上,不需要调用PowerShell-native命令;例如:
      ConvertFrom-Json '{ "foo": "bar" }' 工作正常。

    • 由于 长期存在的错误 ,您 do 在调用 外部程序,不幸的是 - 为了不破坏向后兼容性而尚未修复的问题 - 请参阅 了解背景信息和未来可能的修复。