我的JSON文档jsonStr
中有一个shell脚本。我试图在反序列化jsonStr后使用Python子进程模块执行该shell脚本 -
#!/usr/bin/python
import subprocess
import json
jsonStr = '{"script":"#!/bin/bash \\n STRING="Hello World" \\n echo $STRING \\n"}'
j = json.loads(jsonStr)
print "start"
subprocess.call(j['script'], shell=True)
print "end"
但不管怎样,每当我运行上面的python脚本时,我总会得到这样的错误 -
Traceback (most recent call last):
File "shellscript", line 27, in <module>
j = json.loads(jsonStr)
File "/usr/lib/python2.7/json/__init__.py", line 326, 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 , delimiter: line 1 column 34 (char 34)
有什么想法,我在这里做错了什么?
答案 0 :(得分:2)
似乎JSON解析器被“内部”混淆,特别是在它说出hello world的地方。
通过向python JSON库询问正确的字符串,可以优雅地获得所有JSON转义规则。
import json
jsoncnt = {'script':'#!/bin/bash \n STRING="Hello World" \n echo $STRING \n'}
jsonStr = json.dumps(jsoncnt)
print jsonStr
q = json.loads(jsonStr)
答案 1 :(得分:1)
JSON格式错误。应该是:
jsonStr = '{"script":"#!/bin/bash \\n STRING=\\"Hello World\\" \\n echo $STRING \\n"}'
答案 2 :(得分:1)
这对我很好..
import subprocess
import json
json_dict = {"script":'#!/bin/bash \\n STRING="Hello World" \\n echo $STRING \\n'}
dump = json.dumps(json_dict)
j = json.loads(dump)
print j
print j['script']
print "start"
subprocess.call(j['script'], shell=True)
print "end"
你可以粘贴代码如何使用json.dumps()
结果:
{u'script': u'#!/bin/bash \\n STRING="Hello World" \\n echo $STRING \\n'}
#!/bin/bash \n STRING="Hello World" \n echo $STRING \n
start
end
答案 3 :(得分:1)
JSON中不允许使用双引号字符(“)。您应该使用这样的转义单引号替换它:
jsonStr = '{"script":"#!/bin/bash \\n STRING=\'Hello World\' \\n echo $STRING \\n"}'