admin 管理员组

文章数量: 1184232


2024年4月13日发(作者:ifonts字体)

linux jq 的用法

英文回答:

Linux jq is a command-line tool that is used for

parsing and manipulating JSON data. It is a lightweight and

flexible tool that can be used to extract specific data

from JSON files, filter and transform JSON data, and

perform various operations on JSON objects.

One of the most common use cases for jq is to extract

specific data from a JSON file. For example, let's say we

have a JSON file called "" that contains

information about books. We can use jq to extract the

titles of all the books in the file by running the

following command:

jq '.[].title' .

This command uses the "." operator to select all

elements in the JSON array, and then uses the "title" key

to extract the title of each book. The result will be a

list of book titles.

Another useful feature of jq is its ability to filter

JSON data based on certain conditions. For example, let's

say we want to filter the books in our "" file and

only select the ones that have a rating higher than 4. We

can use the following command:

jq 'map(select(.rating > 4))' .

This command uses the "map" function to iterate over

each element in the JSON array, and the "select" function

to filter out the books with a rating higher than 4. The

result will be a new JSON array that only contains the

selected books.

In addition to extracting and filtering data, jq also

provides various functions for transforming and

manipulating JSON data. For example, we can use the "map"

function to modify the structure of the JSON data. Let's

say we want to add a new key called "discounted_price" to

each book in our "" file, which is calculated by

subtracting 10% from the original price. We can use the

following command:

jq 'map(.discounted_price = .price 0.9)' .

This command uses the "map" function to iterate over

each element in the JSON array, and the assignment operator

"=" to add a new key-value pair to each book object. The

result will be a new JSON array with the discounted prices

added to each book.

中文回答:

Linux jq是一个用于解析和操作JSON数据的命令行工具。它

是一个轻量级且灵活的工具,可以用于从JSON文件中提取特定数据,

过滤和转换JSON数据,以及对JSON对象执行各种操作。

jq最常见的用例之一是从JSON文件中提取特定数据。例如,

假设我们有一个名为""的JSON文件,其中包含有关图书

的信息。我们可以使用jq通过运行以下命令来提取文件中所有书籍

的标题:

jq '.[].title' .

该命令使用"."运算符选择JSON数组中的所有元素,然后使用

"title"键提取每本书的标题。结果将是一个书籍标题的列表。

jq的另一个有用功能是根据特定条件过滤JSON数据。例如,

假设我们想要过滤""文件中的书籍,并只选择评分高于4

的书籍。我们可以使用以下命令:

jq 'map(select(.rating > 4))' .

该命令使用"map"函数遍历JSON数组中的每个元素,并使用

"select"函数过滤掉评分高于4的书籍。结果将是一个只包含所选

书籍的新JSON数组。

除了提取和过滤数据外,jq还提供了各种函数来转换和操作

JSON数据。例如,我们可以使用"map"函数来修改JSON数据的结构。

假设我们想要在""文件的每本书中添加一个名为

"discounted_price"的新键,该键通过从原始价格中减去10%来计

算。我们可以使用以下命令:

jq 'map(.discounted_price = .price 0.9)' .

该命令使用"map"函数遍历JSON数组中的每个元素,并使用赋

值运算符"="将一个新的键值对添加到每个书籍对象中。结果将是一

个新的JSON数组,其中包含了每本书的折扣价格。


本文标签: 数据 文件 书籍 使用 函数