2016-02-02 9 views
31

Dato il seguente comando JQ e JSON:Come si usa jq per convertire il numero in stringa?

jq '.[]|[.string,.number]|join(": ")' <<< ' 
[ 
    { 
    "number": 3, 
    "string": "threee" 
    }, 
    { 
    "number": 7, 
    "string": "seven" 
    } 
] 
' 

Sto cercando di formattare l'output come:

three: 3 
seven: 7 

Purtroppo, il mio tentativo è risultato il seguente errore:

jq: error: string and number cannot be added

Come si converte il numero in stringa in modo che entrambi possano essere uniti?

risposta

35

Il comando jq ha la funzione tostring. Mi ci è voluto un po 'per imparare ad usarlo per tentativi ed errori. Ecco come usarlo:

jq -r '.[] | [ .string, .number|tostring ] | join(": ")' <<< ' 
[{ "number": 9, "string": "nine"}, 
{ "number": 4, "string": "four"}] 
' 
nine: 9 
four: 4 
3

Un'alternativa e forse più intuitivo formato è:

jq '.[] | .string + ": " + (.number|tostring)' <<< ... 

Da segnalare la necessità di parentesi intorno .number|tostring.

Problemi correlati