将JSON文本作为命令行参数传递 [英] Passing json text as command line argument

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

问题描述

我正在尝试将以下JSON文本传递到我的python代码中.

I am trying to pass the following JSON text into my python code.

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

我的代码如下.

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

在Windows 10 PowerShell上运行以下命令时,

When running the following on Windows 10 PowerShell,

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

我得到以下信息:

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)

据我所知,我接受了我的代码,并正确地传递了JSON文本.我不知道我在做什么错.我知道JSON文本有效(已通过 https://jsonlint.com/进行了检查).谢谢.

As far as I know, I take my code, and pass the JSON text properly. I can't figure out what I'm doing wrong. I know the JSON text is valid (checked with https://jsonlint.com/). Thanks.

推荐答案

所以我知道了.

sys.argv[1]

上一行是将我的Json文本带到下面,并从中删除引号.

The above line was taking my Json text below and taking out the quotes from it.

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

进入

{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.

这篇关于将JSON文本作为命令行参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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