2

I'm trying to write a json dumps string using linux bash shell echo in a text file. My problem is it removes all double quotes.

example code.

d = {"key": "value"}
"echo %s > /home/user/%s" % (simplejson.dumps(d), 'textfile'))

Output in textfile

{key: value}

It removes all double quotes so I can't load it to json because it is not a valid json anymore.

Thanks

unice
  • 2,655
  • 5
  • 43
  • 78
  • 2
    Why don't you write to the file directly from Python, instead of generating bash code? – Barmar Feb 06 '15 at 03:17
  • possible duplicate of [escape a string for shell commands in Python](http://stackoverflow.com/questions/18116465/escape-a-string-for-shell-commands-in-python) – Barmar Feb 06 '15 at 03:20
  • @Barmar I'm using paramiko to write the textfile to another machine. – unice Feb 06 '15 at 03:27

2 Answers2

3

You need to escape quotes for Bash usage:

("echo %s > /home/user/%s" % (simplejson.dumps(d), 'textfile')).replace('"', '\\"')
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
1

Since you said you're using paramiko, writing to the file directly is perfect. Edited code to reflect paramiko:

You can write to the file directly after logging onto the server, no need to pass in the bash command (which is hackish as is). You will need two try-catch's: one to catch any error in opening the file, the other to catch any write in the file. If you'd prefer an exception to be thrown up in either of those cases, remove the try-catch.

import paramiko

*do your ssh stuff to establish an SSH session to server*

sftp = ssh.open_sftp()
try:
    file = sftp.file('/home/user/textfile', 'a+')
        try:
            file.write(simplejson.dumps(d))
        except IOError:
            ...*do some error handling for the write here*
except IOError:
    ...*do some error handling for being unable to open the file here*
else:
    file.close()
sftp.close()
the_constant
  • 681
  • 4
  • 11