0

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"}
]
4
  • 1
    Why do you want to call a shell function to manipulate JSON inside jq? Why not use jq's own functions? Commented Jul 21, 2022 at 9:55
  • What is your expected output? Commented Jul 21, 2022 at 9:55
  • Expected output is [ {"id":"1","name":"a-a"}, {"id":"2","name":"b-b"}, {"id":"3","name":"c-c"} ] Commented Jul 21, 2022 at 9:56
  • @Inian I am not familiar with the functions that jq provides. Do you mind directing me to any that would help with this?? Thanks! Commented Jul 21, 2022 at 9:59

1 Answer 1

1

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

jq '.[].name |= sub("\\."; "-")' file.json
Sign up to request clarification or add additional context in comments.

1 Comment

Presumably gsub would be the appropriate function to use here, in general.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.