Home > Back-end >  String Manipulation within a JSON array using jq
String Manipulation within a JSON array using jq

Time:07-21

I am writing a bash script and I am looking to replace a character within a JSON field in a JSON array. In this case, I am trying to change the "." (period) character to a "-" (hyphen) in the name field. I am using jq to parse my JSON. Any tips on how I can achieve this will greatly help. Thank you!

Bash Script so far:

RAW=$(curl ${URL})

function manip() { 
    # Function for string manipulation.
}

echo "${RAW}" | jq '.data | .[].name = $manip' # Unable to make a function call in there.

Sample JSON:

[
    {"id":"1","name":"a.a"},
    {"id":"2","name":"b.b"},
    {"id":"3","name":"c.c"}
]

Expected Output:

[
    {"id":"1","name":"a-a"},
    {"id":"2","name":"b-b"},
    {"id":"3","name":"c-c"}
]

CodePudding user response:

To replace a dot with a dash, use the sub function:

jq '.[].name |= sub("\\."; "-")' file.json
  • Related