简体   繁体   English

将json文本作为命令行参数传递

[英]Passing json text as command line argument

I am trying to pass the following JSON text into my python code. 我试图将以下JSON文本传递给我的python代码。

{"platform": "android", "version": "6.0.1"}

My code is as follows. 我的代码如下。

import sys
import json
data = json.loads(sys.argv[1])
print(str(data))

When running the following on Windows 10 PowerShell, 在Windows 10 PowerShell上运行以下时,

python jsonTest.py '{"platform": "android", "version": "6.0.1"}'

I get the following: 我得到以下内容:

Traceback (most recent call last):
File "jsonTest.py", line 3, in <module>
data = json.loads(sys.argv[1])
File "C:\Users\Rishabh Bhatnagar\AppData\Local\Programs\Python\Python36-
32\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\Rishabh Bhatnagar\AppData\Local\Programs\Python\Python36-
32\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Rishabh Bhatnagar\AppData\Local\Programs\Python\Python36-
32\lib\json\decoder.py", line 355, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double 
quotes: line 1 column 2 (char 1)

As far as I know, I take my code, and pass the JSON text properly. 据我所知,我接受了我的代码,并正确传递了JSON文本。 I can't figure out what I'm doing wrong. 我无法弄清楚我做错了什么。 I know the JSON text is valid (checked with https://jsonlint.com/ ). 我知道JSON文本是有效的(使用https://jsonlint.com/查看)。 Thanks. 谢谢。

So I figured it out. 所以我明白了。

sys.argv[1]

The above line was taking my Json text below and taking out the quotes from it. 上面的一行是我的Json文本,并从中取出引号。

{"platform": "android", "version": "6.0.1"}

into

{platform: android, version: 6.0.1}

My workaround is to run it as follows. 我的解决方法是按如下方式运行它。

Python jsonTest.py '{\"platform\": \"android\", \"version\": \"6.0.1\"}'

I will try to find a better way, but for today, I'm done. 我会尽力找到更好的方法,但就今天而言,我已经完成了。

import sys
import json
data = json.loads(sys.argv[1].replace("'", '"'))
print(str(data))

This seems to work for me, python 3.6 when calling with python jsonTest.py "{'platform': 'android', 'version': '6.0.1'}" 这对我来说似乎python jsonTest.py "{'platform': 'android', 'version': '6.0.1'}"用,python 3.6用python jsonTest.py "{'platform': 'android', 'version': '6.0.1'}"调用python jsonTest.py "{'platform': 'android', 'version': '6.0.1'}"

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

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