json - 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.
解决方案
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"
]
推荐阅读
- c++ - 是否可以使用 std 库的 find、begin 和 end 编写 in_array 辅助函数?
- jquery - 克隆 div 复制后不可拖动
- django - 我想在我的网站上添加结构等标签
- python - cv2.imshow() 函数在用户输入时不显示图像,否则工作
- node.js - Meteor + 乘客 + Nginx 的 Segfault
- c# - 在单击服务器端按钮事件后,无法在更改事件上使用 Jquery 获取文本框值?
- spring-mvc - 如何优化这个控制器和 Thymeleaf-View?
- powershell - 变量powershell的新值
- java - 如何在 MpChart 的 BarChart 中使 bar 独立且不相关?
- javascript - 如何使用 InboxSDK 在 Gmail 和其他网站上运行 chrome 扩展程序?