I am trying to pass JSON as an argument to python script in command prompt. It works if the element in JSON does not have white spaces in value but it does not work if there are white spaces.
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. I have spaces in values e.g. 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
# 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
python script.py '{""name"":""Jon Snow"",""kingdom"":""Winterfell"",""slogan"":""King in theNorth""}'