1

I have a shell script in my JSON document jsonStr.. I am trying to execute that shell script using Python subprocess module after deserializing the jsonStr -

#!/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"

But somehow whenever I run my above python script, I always get an error like this -

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)

Any thoughts what wrong I am doing here?

0

4 Answers 4

2

It seems the JSON parser is being confused by a " inside a ", particularly where it says hello world.

Observe that all the JSON escaping rules can be elegantly obtained by just asking the python JSON library for the correct string.

import json
jsoncnt = {'script':'#!/bin/bash \n STRING="Hello World" \n echo $STRING \n'}
jsonStr = json.dumps(jsoncnt)
print jsonStr
q = json.loads(jsonStr)
Sign up to request clarification or add additional context in comments.

Comments

2

It is woking fine for me..

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"

can you please paste code How u r using json.dumps()

Result:

{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

1 Comment

No it isn't. Observe that in the OP's code your json_dict is a string not a dictionary.
1

Wrong JSON format.It should be:

jsonStr = '{"script":"#!/bin/bash \\n STRING=\\"Hello World\\" \\n echo $STRING \\n"}'

Comments

1

Double quote character (") is not allowed inside JSON. You should substitute it with escaped single quote like this:

jsonStr = '{"script":"#!/bin/bash \\n STRING=\'Hello World\' \\n echo $STRING \\n"}'

Comments

Your Answer

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