Using a pared-down sample JSON object with just the relevant key:
$ cat test.json
{
"drop_reasons": ["a","b","c"]
}
$ jq '.drop_reasons |= join(",")' test.json
{
"drop_reasons": "a,b,c"
}
Your sample with an empty array would change to an empty string.
x |= y is essentially shorthand for x = (x | y). The parens are what you were missing in your attempt; they're needed because of jq precedence rules.
Using a pared-down sample JSON object with just the relevant key:
$ cat test.json
{
"drop_reasons": ["a","b","c"]
}
$ jq '.drop_reasons |= join(",")' test.json
{
"drop_reasons": "a,b,c"
}
Your sample with an empty array would change to an empty string.
x |= y is essentially shorthand for x = (x | y). The parens are what you were missing in your attempt; they're needed because of jq precedence rules.
I'm not familiar with jq, but if you just replace every "," with ,, it does the trick. It's a hack, so it could break if the input data changes format.
$ cat temp.txt
drop_reasons=["a","b","c"]
$ perl -pe 's/","/,/g' temp.txt
drop_reasons=["a,b,c"]
Transform a list of strings to JSON array using jq - Stack Overflow
bash - convert JSON array to space separated string - Unix & Linux Stack Exchange
json - Using jq to convert array of strings into array of objects - Stack Overflow
How to filter using jq array of strings which contains a specific value - Stack Overflow
You're making it a lot more complicated than it is. Just use map() and |=:
jq 'map(.tags |= split(" "))' file.json
Edit:
If you want to handle entries without tags:
jq 'map(try(.tags |= split(" ")))' file.json
Alternatively, if you want to keep unchanged all entries without tags:
jq 'map(try(.tags |= split(" ")) // .)' file.json
Result:
[
{
"tags": [
"tagA",
"tag-B",
"tagC"
],
"title": "Some Title"
},
{
"tags": [
"tagA",
"tagC"
],
"title": "Some Title 2"
}
]
You can attempt this is sed as follows:
The code below is using GNU version of sed (although it can be portably written in POSIX-compatible as well)
sed -e '
/[{]/,/[}]/!b
/"tags":/!b
h;s/"tags":/&\n/;s/\n.*/ /;s/./ /g;x
s/"tags":/&\n/
:a
s/\(\n.*\)\([^"]\) \([^"]\)/\1\2","\3/;ta
y/\n/[/;s/$/]/;G
:b
s/","\(.*\)\(\n.*\)/",\2"\1\2/;tb
s/\(.*\)\n.*/\1/
' yourjsonfile
Working
- We select the range as
{to the next}lines. - Zoom in on
"tags"line in the range selected. - Compute the nesting spaces for the given tag and store it in hold.
- Double quote the tag data in a loop
:a - Insert the nesting spaces after the
,in a loop:b - Remove everything after the last newline in the pattern space & print.
Results
[
{
"title": "Some Title",
"tags":["tagA",
"tag-B",
"tagC"]
},
{
"title": "Some Title 2",
"tags":["tagA",
"tagC"]
},
...
]