Format number in thousands separators with jq json cli

less than a minute read 06-10-2024
Format number in thousands separators with jq json cli


Formatting Numbers with Thousands Separators in jq: A Concise Guide

Working with JSON data on the command line can be a breeze with jq, a powerful JSON processor. But what if you need to format large numbers in a user-friendly way, adding thousands separators? jq provides a simple and elegant solution.

The Problem: You have a JSON file containing numbers that are cumbersome to read, such as:

{
  "population": 123456789,
  "revenue": 9876543210
}

The Goal: You want to format these numbers with thousands separators, like this:

{
  "population": "1,234,567,890",
  "revenue": "9,876,543,210"
}

The Solution: jq offers a built-in function called tostring that can be used to format numbers. Here's the simple code snippet to achieve our goal:

.population |= tostring
.revenue |= tostring

Explanation:

  • .population |= tostring: This line selects the population field and applies the tostring function to it. The |= operator modifies the value in place.
  • .revenue |= tostring: This line does the same for the revenue field.

Example:

Let's say your JSON data is in a file named data.json. You can apply the jq command like this:

jq '.population |= tostring; .revenue |= tostring' data.json

This will output the formatted JSON data to your terminal.

Additional Insights:

  • Locale-Specific Formatting: By default, tostring uses the locale settings of your system to determine the thousands separator. If you need a specific format, you can use the format function in jq.
  • Multiple Fields: If you need to format multiple numbers in your JSON data, simply chain the |= tostring operation for each field.

Conclusion:

jq's tostring function offers a simple and effective way to format numbers with thousands separators. This makes your JSON data more readable and easier to understand. Remember to tailor the code to your specific data structure and desired formatting.

Further Reading and Resources: