Using jq:
$ jq '.topics[0].topic |= "test_1"' file.json
{
"topics": [
{
"topic": "test_1"
}
],
"version": 1
}
This reads the JSON document and modifies the value of the topic entry of the first element of the array topics to the string test_1.
If you have your value in a variable (encoded in UTF-8):
$ val='Some value with "double quotes"'
$ jq --arg string "$val" '.topics[0].topic |= $string' file.json
{
"topics": [
{
"topic": "Some value with \"double quotes\""
}
],
"version": 1
}
Using Perl:
$ perl -MJSON -0777 -e '$h=decode_json(<>); $h->{topics}[0]{topic}="test_1"; print encode_json($h), "\n"' file.json
{"topics":[{"topic":"test_1"}],"version":1}
With a variable:
$ val='Some value with "double quotes"'
$ STRING=$val perl -MJSON -0777 -e '$string = $ENV{STRING}; utf8::decode $string; $h=decode_json(<>); $h->{topics}[0]{topic}=$string; print encode_json($h), "\n"' file.json
{"topics":[{"topic":"Some value with \"double quotes\""}],"version":1}
Both of these uses the Perl JSON module to decode the JSON document, change the value that needs changing, and then output the re-encoded data structure. The error handling is left as an exercise.
For the second piece of code, the value to be inserted is passed as an environment variable, STRING, into the Perl code. This is due to reading the JSON document from file in "slurp" mode with -0777.
”(U+201D,RIGHT DOUBLE QUOTATION MARK) instead of a json quote (", U+0022,QUOTATION MARK)