首页 > 解决方案 > 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.

标签: jsonbashawkjq

解决方案


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"
]

推荐阅读