1

I would like to write JSON Output into my python models.

My Model:

class Thing(models.Model):
    name = models.CharField(max_length=50)
    serial = models.BigIntegerField()
    san = models.CharField(max_length=50)
    validfrom = models.CharField(max_length=50)
    validto = models.CharField(max_length=50)
    requester = models.CharField(max_length=50)
    def __unicode__(self):
       return self.name

This is my JSON Output:

 {
    "Serial Number":  "123132213",
    "SAN":  "hfdhfg",
    "Valid From":  "  04.08.2015 18:43",
    "Valid To":  "  03.08.2020 18:43",
    "URL":  "https://url.com/3212"
 }

I'm executing a command that gives me this output which I try to save into my model.

# Execute command & read 
        stdin,stdout,stderr=ssh.exec_command(cmd)
        outlines=stdout.readlines()
        resp=''.join(outlines)
        print(resp)

        # Load JSON Output and save into model
        jsonToPython = json.loads(resp)
        thing_ser.validated_data['serial'] = jsonToPython['Serial Number']
        thing_ser.validated_data['san'] = jsonToPython['Serial Number']
        thing_ser.validated_data['validfrom'] = jsonToPython['Valid From']
        thing_ser.validated_data['validto'] = jsonToPython['Valid To']

        thing_ser.save()

I think this doesn't work because my JSON is not a string and json.loads excepts a string, so I'm not sure what's the right approach to this.

Kermit Christmas
  • 113
  • 2
  • 15

1 Answers1

0

resp should be a string. I don't think this is a JSON issue. I'm not an expert on the ssh.exec_command() method (I'm assuming you're using paramiko?), but I think you aren't getting a valid JSON string in resp when you should be... Maybe this SO question is relevant, particularly in suggesting that your cmd is problematic. If cmd is a string, try adding a newline to it to ensure that your command is actually running and not just being typed in and then sitting in the ssh terminal:

stdin, stdout, stderr = ssh.exec_command(cmd + '\n')

Also, can you provide more info on the resp variable? What does print resp do? And what about print type(resp)?

Brendan Goggin
  • 2,061
  • 14
  • 14
  • Yes I'm using paramiko to start a ssh connection and execute a powershell script. My CMD is cmd= 'powershell.exe -file C:\\Powershell\\\\script.ps1 -CN %s'. The Json output I'm getting i build into the powershell script. If i do a print(resp) i get something like this { "Serial Number": " 1223", "SAN": " fewfew", "Valid From": " 08.08.2017 14:41", "Valid To": " 07.08.2020 14:41", "URL": "https://url.com/fewfew-" } – Kermit Christmas Aug 08 '17 at 12:49
  • Please add in `print type(resp)`, but it sounds like it might already be a dict, in which case you could just do `thing_ser.validated_data['serial'] = resp['Serial Number']`, etc. – Brendan Goggin Aug 08 '17 at 12:59
  • i found the error, had to add import ast and dict = ast.literal_eval(resp) to get it working – Kermit Christmas Aug 08 '17 at 17:43