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.
我想从终端运行python脚本时传递JSON作为参数。我可以从终端传递JSON对象吗?但是,我只能从终端传递字符串,但我需要JSON而不是它。
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.
但是,如果我想要JSON,它会给出错误。我尝试使用以下内容来传递json。
$ python test.py { 'a':1, 'b':2 }
1 个解决方案
#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)])
#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)])