Parse only given values to command line via Python
<p>I'm sending I'm receiving a JSON message through MQTT in Python, and I would like to start a command line program with what the JSON gives as variables.</p>

<p>The problem with this is that I don't know what values are going to come through and thus this is where I have trouble.</p>

<p>The easiest would be if I knew all the variables that would come through and do something like this:</p>

<pre><code>data = json.loads(msg.payload)
os.system("'command +f ' + data[arg1] + ' +g ' + data[arg2]")
</code></pre>

<p>But as mentioned previously, I don't know if they are being passed through, and as such, how can I break it down so that the command line command is build up?</p>

<p>Maybe:</p>

<pre><code>    if 'arg1' in data:
            command = "+f " + data[arg1]
    else:
            pass
    if 'arg2' in data:
            command + "+g " + data[arg2]
    else:
            pass
</code></pre>

<p>Would this work? Is there a better idea?</p>

<p>You can use a for loop to iterate over the json, and construct the command string.</p>

<pre><code> commandArgs = ["+f ","+g "]
 commandCount=0
 for element in data:
    command= command + commandArgs[commandCount] + element
    commandCount = commandCount +1
</code></pre>

python json mqtt