0

I am currently tring to work with import a json input that is accepted by Python through a commandline argument and I am trying to save the different values to JSON to a list. I am having issues with my code given below and have attached both the code and the error I get below. Any help much appreciated.

import sys
import json
def lookup1 ():
    jsonData = json.loads(sys.argv[1])
    print jsonData
    jsonList = [jsonData['proxy'],jsonData['OS']]
    print jsonList

lookup1()

The error is given below:

$ python dynamicMapper.py '{'proxy':1,'OS':2}'
Traceback (most recent call last):
  File "dynamicMapper.py", line 9, in <module>
    lookup1()
  File "dynamicMapper.py", line 4, in lookup1
    jsonData = json.loads(sys.argv[1])
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

The commadline argunet that I give is python dynamicMapper.py '{'proxy':1,'OS':2}' I am not able to find out what is causing this error and if my approach is right.

1 Answer 1

2

The script is working fine, you just need to call it the right way:

python dynamicMapper.py '{"proxy":1,"OS":2}'
{u'OS': 2, u'proxy': 1}
[1, 2]

In JSON the strings are quoted with double quotes instead of single quotes. You also need to quote the string passed to script so that shell understands it being a single argument.

Sign up to request clarification or add additional context in comments.

2 Comments

ah, thanks! I guess what was wrong was the way I called it. I was using python dynamicMapper.py {'proxy':1,'OS':2}. I though single and double quotes were interchangeable. Probably not in a dict, Is that right?
@lordlabakdas You're not passing a dict to to the script but a string containing JSON that your script then parses with json.loads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.