简体   繁体   English

使用空格传递 Python JSON 参数

[英]Passing Python JSON argument with whitespace

I am trying to pass JSON as an argument to python script in command prompt.我试图在命令提示符下将 JSON 作为参数传递给 python 脚本。 It works if the element in JSON does not have white spaces in value but it does not work if there are white spaces.如果 JSON 中的元素在值中没有空格,则它有效,但如果有空格,则它不起作用。

Here is script这是脚本

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'])

Passing below JSON as an argument in the power Shell.在 Power Shell 中将 JSON 作为参数传递到下面。 I have spaces in values eg Jon Snow我在值中有空格,例如 Jon Snow

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

Output:输出:

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)

Please any advise to fix it.请任何建议来修复它。

If you use \\" it means the enclosing quotes are double quotes too. On windows the enclosing simple quotes doesn't work so the 2 options are如果您使用\\"则表示封闭引号也是双引号。在 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 case Powershell 案例

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

In PowerShell :PowerShell 中

  • There is de facto nothing fundamentally wrong with your attempt to escape the embedded " characters as \\" for a call to an external program (such as Python), despite their being enclosed in single -quoted string ( '...' ):实际上,您尝试将嵌入的"字符转义为\\"以调用外部程序(例如 Python)从根本上没有任何错误尽管它们被包含在引号字符串'...' )中:

    • Due to an additional bug in Windows PowerShell (in addition to the fundamental bug discussed below) that has since been fixed in PowerShell [Core] v6+ , a string with \\" escapes only works if it contains at least one space character .由于Windows PowerShell 中的一个额外错误(除了下面讨论的基本错误之外),该错误已在PowerShell [Core] v6+ 中修复,带有\\"转义的字符串仅在包含至少一个空格字符时才有效。

    • In other words: In PowerShell [Core] v6+ , your command would work as-is ;换句话说:在PowerShell [Core] v6+ 中,您的命令将按原样运行 in Windows PowerShell , it would only work if your string contained at least one space character .Windows PowerShell 中,它只有在您的字符串至少包含一个空格字符时才有效

    • Since in this particular context (only!) \\" and "" are interchangeable and use of "" also works with space- less strings in Windows PowerShell, "" -escaping , as shown in azro's helpful answer , is the more robust choice; the caveat is that most, but not all CLIs on Windows recognize "" as an escaped " char., whereas those that don't do recognize \\" .因为在这个特定背景下(仅!) \\"""可以互换和使用""还与在Windows PowerShell中节省空间更少的字符串, "" -escaping,如图azro的有用的答案,是更强大的选择;需要注意的是,Windows 上的大多数但并非所有CLI""识别为转义的" char.",而那些不识别\\" 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\"}'
  • There should be something wrong , however, because you shouldn't have to escape " chars. inside a '...' -delimited string literal , which is a verbatim string literal in PowerShell .但是,应该有问题,因为您不必在'...'分隔的字符串文字中转义"字符。这是PowerShell 中逐字字符串文字

    • In fact, you don't need to do it if you call PowerShell-native commands ;其实,并不需要,如果你调用PowerShell的本地命令去做; eg:例如:
      ConvertFrom-Json '{ "foo": "bar" }' works just fine. ConvertFrom-Json '{ "foo": "bar" }'工作得很好。

    • Due to a longstanding bug , you do have to do it when calling external programs , unfortunately - something that hasn't been fixed yet so as not to break backward compatibility - see this answer for background information and a possible future fix.由于长期存在的错误,您在调用外部程序确实必须这样做,不幸的是- 尚未修复以免破坏向后兼容性 - 有关背景信息和可能的未来修复,请参阅此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM