Ravi Shanker Reddy
Ravi Shanker Reddy

Reputation: 495

Need JSON output in return of Salt-api

   request({
        url: "https://xx.xxx.xxx.xxx:9999/run",
        headers: {
            'Accept': 'application/x-yaml',
            'X-Auth-Token': "41b9539436faae8016c305c2f875b31e47a23d93",
            'Content-type': 'application/json',
        },
        method: "POST",
        json: true,
        body: [{
            "client": "local",
            "tgt": "master_minion",
            "fun": "cmd.script",
            "kwarg": {"source": "salt://update-diff.py", "args":args},
            "username": "salt",
            "password": "salt",
            "eauth": "pam"
        }]
    }

I am passing a request to salt-api to run a script. I need to parse the output.

Sample output:

return:
- master_minion:
    pid: 28796
    retcode: 0
    stderr: ''
    stdout: " sadfh,smfsdhg\n sfgmsfgmsg\n sfgmsfgmsg\n-dkfadnfklad--->New123\n+dkfadnfklad--->New1232\n\
      \ sdfjhs,dfhn\n sdfjhs,dfhn\n sdfjhs,dfhn"

Can I get these output in JSON??

I want all lines in an array like below:

Expected Output: ["sadfh,smfsdhg"," sfgmsfgmsg"," sfgmsfgmsg","-dkfadnfklad--->New123","+dkfadnfklad--->New1232"," sdfjhs,dfhn"," sdfjhs,dfhn"," sdfjhs,dfhn"]

Any suggestions?? Thanks in Advance

Upvotes: 0

Views: 1259

Answers (1)

zwobot
zwobot

Reputation: 41

To get JSON returned from salt-api you just need to change the Accept-type in your request header:

  request({
        url: "https://xx.xxx.xxx.xxx:9999/run",
        headers: {
            'Accept': 'application/json',
  ...

Then you will get something like:

{
    "return": [
        {
            "master_minion": {
                "pid": 28796,
                "retcode": 0,
                "stderr": "",
                "stdout": " sadfh,smfsdhg\n sfgmsfgmsg\n sfgmsfgmsg\n-dkfadnfklad--->New123\n +dkfadn--->New1232\n  sdfjhs,dfhn\n sdfjhs,dfhn\n sdfjhs,dfhn"
            }
        }
    ]

}

From your expected output, I asume that is not what you want. But your expected output is not JSON. JSON is a key value based datatructure like a python dictionary. You expect something like a list. A list like you expect can be part of JSON but need a key:

{ "key": ["sadfh,smfsdhg"," sfgmsfgmsg"," sfgmsfgmsg","-dkfadnfklad--->New123","+dkfadnfklad--->New1232"," sdfjhs,dfhn"," sdfjhs,dfhn"," sdfjhs,dfhn"] }

The salt-api can not format the stdout of a executed script from a arbitrary string to JSON (how should it know that \n is a marker for a list item). You need to do it by yourself by formatting the output in update-diff.py script to json (in the script). Even then you will only get a the a string with JSON in it for the key stdout, but you can easily extract it and continue with you processing.

Upvotes: 1

Related Questions