Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify a key-value in a json using jq in-place

Tags:

json

bash

shell

jq

I have a json in which I want to modify a particular value but the terminal always displays the json with the modified value but it does not actually change the value in the particular file. Sample json:

{    name: 'abcd',    age: 30,    address: 'abc' } 

I want to change the value of address in the file itself but so far I've been unable to do so. I tried using:

jq '.address = "abcde"' test.json 

but it didn't work. Any suggestions?

like image 406
wolfsbane Avatar asked Mar 10 '17 10:03

wolfsbane


People also ask

Can jq edit JSON?

jq is equally useful for updating existing JSON data. I want to create a release script that will read the existing JSON file and output to an updated document that has the new path for the command and the new VERSION environment variable.

Does jq use JSONPath?

JSONPath distinguishes between the "root object or element" ($) and "the current object or element" (.). jq simply uses . to refer to the current JSON entity and so it is context-dependent: it can refer to items in the input stream of the jq process as a whole, or to the output of a filter.


1 Answers

Use a temporary file; it's what any program that claims to do in-place editing is doing.

tmp=$(mktemp) jq '.address = "abcde"' test.json > "$tmp" && mv "$tmp" test.json 

If the address isn't hard-coded, pass the correct address via a jq argument:

address=abcde jq --arg a "$address" '.address = $a' test.json > "$tmp" && mv "$tmp" test.json 
like image 195
chepner Avatar answered Oct 21 '22 07:10

chepner