用空格传递Python JSON参数 [英] Passing Python JSON argument with whitespace

查看:112
本文介绍了用空格传递Python JSON参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在命令提示符下将JSON作为参数传递给python脚本.如果JSON中的元素的值中没有空格,则它可以工作,但是如果有空格,则它不起作用.

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.

这是脚本

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

在Power Shell中在JSON下面作为参数传递.我的值中有空格,例如乔恩·雪诺

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\"}'

输出:

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.

推荐答案

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

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保护壳

Powershell case

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

这篇关于用空格传递Python JSON参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆