Moazzem Hossen
Moazzem Hossen

Reputation: 2516

Conditionally insert a line in JSON array like file with awk

I want to push items with awk to a myArray.json file like so

[
 item1,
 item2
]

To add item1 I tried

echo -e "[\n]" > myArray.json # Create an empty JSON array with "\n"
awk -v var="item1" '/\]/ {print var} 1' myArray.json >> myArray-tmp.json
mv myArray-tmp.json myArray.json

If I now comment out echo -e "[\n]" > myArray.json line (or conditionally skip it), set var="item2" and run the script, item2 is added to the array. I want to add a comma after first line, but not second.

Upvotes: 1

Views: 772

Answers (3)

Dmitry
Dmitry

Reputation: 1293

also, one easy alternative - a walk-path based unix utility jtc to manipulate json.

In jtc there's an option to apply changes right into the source file - -f (without it, the result will only be printed to the console):

bash $ jtc myArray.json 
[
   "item1"
]
bash $ 
bash $ jtc -f -i'"item2"' myArray.json 
bash $ 
bash $ jtc myArray.json 
[
   "item1",
   "item2"
]
bash $ 

Note: inserted element must be a valid JSON - hence double quotes (”item2” - that makes a valid JSON string) and to preserve them (escape shell interpolation) - there are outer single quotes around the argument

PS> Disclosure: I'm the creator of the jtc - shell cli tool for JSON operations

Upvotes: 1

Moazzem Hossen
Moazzem Hossen

Reputation: 2516

jq is a great tool so I upvoted and accepted answer. Here's my ugly way.

[
 item1
 ,item2
]   

I needed to do conditional to skip first two lines after first item has been added. Run this line instead.

awk -v var="item2" '/\]/ {print ","var} 1' myArray.json >> myArray-tmp.json

Upvotes: 1

Rorschach
Rorschach

Reputation: 32446

As a possibly simpler alternative, you could just use jq. So, if you had the json file, myArray.json

[ "item1" ]

You can add additional elements simply with

jq '. + ["item2"]' myArray.json

which should result in

[
  "item1",
  "item2"
]

Upvotes: 2

Related Questions