I need to edit a JSON file, using sed
, to add some data in to the file. The JSON is as follows:
{
'name':
// more attributes that are already filled in
}
I have written this sed
command to try and do it:
sed "s/(\'name\':)/\1\"hello\"\,/g" /path/to/file.json
However, I keep getting this error:
sed: \1 not defined in the RE
The expected results are:
{
'name': "hello",
// more attributes here, left untouched
}
I know this is a bad way of doing it, but I don't think I am able to use tools such as jq
because the file will be edited on a server and I cannot install jq
on the server. If anyone has a better solution i'd be very interested to hear it. Thank you!
As you stated, sed
is not the right tool here, instead, use a proper JSON parser :
$ cat json
{
"name": "foobar"
}
$ jq '.name |= "qux"' json | tee json
(the latest with tee work with small files)
perl -i -MJSON -0ne '
my $DS = decode_json $_;
$DS->{name} = "qux";
print encode_json $DS
' json
remove the -i
switch if you want to test the command without editing the file in place
$ cat json
{
"name": "qux"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With