2

I want to pass JSON as a parameter while running the python script from the terminal. Can I pass JSON Object from terminal. However, I can only pass string from the terminal but I need JSON instead of that.

My tried passing string as follows which gave expected result.

   $ python test.py 'Param1'

But if I want JSON, it gives error.I tried with the following to pass json.

   $ python test.py { 'a':1, 'b':2 }
2
  • 1
    { 'a':1, 'b':2 } isn't valid JSON. But you could pass this is a commandline argument: '{"a":1, "b":2}' Commented Aug 13, 2016 at 16:11
  • Curly brackets have special meaning to the shell. You need to actually use a string value Commented Aug 13, 2016 at 16:28

1 Answer 1

1

Two ways of doing this:

$ cat a.py
import json
import sys
print json.loads(sys.stdin.read().strip())
$ python a.py <<< '{ "a":1, "b":2 }'
{u'a': 1, u'b': 2}
$ echo '{ "a":1, "b":2 }' | python a.py
{u'a': 1, u'b': 2}

$ cat c.py
import json
import sys
print json.loads(sys.argv[1])
$ python c.py '{ "a":1, "b":2 }'
{u'a': 1, u'b': 2}

Follow up (maintaining order):

$ cat d.py
import json
import sys
from collections import OrderedDict
print json.loads(sys.argv[1], object_pairs_hook=OrderedDict)
$ python d.py '{ "a":1, "b":2, "c":3, "d":4 }'
OrderedDict([(u'a', 1), (u'b', 2), (u'c', 3), (u'd', 4)])
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this one. With json having more keys like '{ "a":1, "b":2, "c":3, "d":4 }', I get unordered keys and value pair with json.loads() method. I need a ordered list for json provided in the parameters which I am not getting. Can you help me in this?

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.