乐闻世界logo
搜索文章和话题

How do I update a single value in a json document using jq?

1个答案

1

In the process of updating a single value in a JSON document using jq, you can utilize jq's functions and filters to precisely locate and modify the value you need to update. jq is a powerful command-line JSON processor that allows you to read and update JSON data flexibly.

Here is a specific example demonstrating how to use jq to update a single value in a JSON document:

Assume we have the following JSON file (data.json):

json
{ "name": "Zhang San", "age": 30, "city": "Beijing" }

Now, we want to update the value of age from 30 to 31. Using jq, you can achieve this with the following command:

bash
jq '.age = 31' data.json

This command will output the updated JSON:

json
{ "name": "Zhang San", "age": 31, "city": "Beijing" }

If you want to save the result back to the original file, you can use redirection or jq's -r (raw output) option combined with shell commands. For example:

bash
jq '.age = 31' data.json > temp.json && mv temp.json data.json

Or use sponge from the moreutils package:

bash
jq '.age = 31' data.json | sponge data.json

By doing this, you can flexibly update any value in the JSON document without needing to write complex scripts or manually edit the file.

2024年8月15日 12:01 回复

你的答案