Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

editing a JSON file with sed

Tags:

json

regex

bash

sed

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!

like image 594
Tom Oakley Avatar asked Sep 10 '25 19:09

Tom Oakley


1 Answers

As you stated, sed is not the right tool here, instead, use a proper JSON parser :

INPUT json

$ cat json
{
  "name": "foobar"
}

using jq :

$ jq '.name |= "qux"' json | tee json 

(the latest with tee work with small files)

or using perl :

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

OUTPUT json

$ cat json
{
  "name": "qux"
}
like image 194
Gilles Quenot Avatar answered Sep 13 '25 10:09

Gilles Quenot