I have to update dictionary with new value for existing key in a JSON file.
I need no write new line after existing string using regex
Current file:
{
"id": "aaaa",
"desc": "Service aaa",
"boss":"[email protected]",
"email": [
"[email protected]"
],
desired file:
{
"id": "aaaa",
"desc": "Service aaa",
"boss":"[email protected]",
"email": [
"[email protected]"
"[email protected]"
]
I have this ansible lineinfile module playbook, but I struggle with decent regex. Everything I try just adds new line in the very end of file.
---
- hosts: localhost
gather_facts: no
tasks:
- name: insert line
lineinfile:
path: /home/file.json
state: present
insertafter: " ^ "email": [ "
line: '[email protected]'
How should I write correct regex in this case to write line after the string "email": [ ?
2
Answers
Let’s say current file is aa.txt as follows
Use sed command
Output
Alternatively use AWK
Output
quick comment :
JSON
spec mandates anASCII
comma (","
) between values of arrays (plus your choice of whitespace(s)), so to make the proposed solutions compliant, they would have to resemble this instead—— (snippet directly from
jq
):