Since Python is multiplatform, is important to note differences between Linux and Windows, especially because of how they treat double-quotes/single-quotes differently.
Second, some previous answers are a little bit obsolete: in python2, print
without parentheses was permitted. Nevertheless, in python3, print must be between parentheses.
Linux (bash)
It doesn't matter how you put double/single quotes. Json can be parsed in both ways with "keys" or 'keys'
HOSTNAME=$(curl -s "$HOST" |
python3 -c 'import json,sys;print(json.load(sys.stdin)["hostname"])')
It also works: (pay attention at single/double quote at key)
HOSTNAME=$(curl -s "$HOST" |
python3 -c "import json,sys;print(json.load(sys.stdin)['hostname'])")
Windows (powershell)
Keys in json MUST be between single quotes. Only the following syntax is accepted.
The ConvertTo-Json
function generates object and works with keys between single quotes.
$HOSTNAME=(Invoke-RestMethod $HOST | `
ConvertTo-Json | `
python3 -c "import json,sys; print(json.load(sys.stdin)['hostname'])")