Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing json text as command line argument

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

{"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,

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. I can't figure out what I'm doing wrong. I know the JSON text is valid (checked with https://jsonlint.com/). Thanks.

like image 310
Rishi_B Avatar asked Mar 09 '23 15:03

Rishi_B


2 Answers

So I figured it out.

sys.argv[1]

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

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

like image 68
Rishi_B Avatar answered Mar 11 '23 04:03

Rishi_B


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

like image 44
jacoblaw Avatar answered Mar 11 '23 04:03

jacoblaw