Search code examples
jsonformattingintegerjq

Format number in thousands separators with jq json cli


Given {"a": 1234567890}, I want 1,234,567,890 in the result, how this can be done with jq

echo '{"a": 1234567890}' | jq '.a | FORMAT?'

Thanks for @peak's answer, the solution is

echo '{"a": 1234567890}' | jq -r 'def h: [while(length>0; .[:-3]) | .[-3:]] | reverse | join(","); .a | tostring | h'
//-> 1,234,567,890

Solution

  • Here's an idiomatic one-liner definition:

    def h: tostring | [while(length>0; .[:-3]) | .[-3:]] | reverse | join(",");
    

    Example

    12, 123, 1234, 12345678 | h
    

    Output (using -r option):

    12
    123
    1,234
    12,345,678