I have a simple file like:
keya="valuea valueb"
keyb=""
keyc="valuex"
I would like to convert this file into JSON with following structure:
{
"keya": ["valuea", "valueb"],
"keyb": [],
"keyc": ["valuex"]
}
Is there anyway to perform it using only jq? I was doing this parse on python but I would be glad If was possible to solve all using only jq.
CodePudding user response:
Assuming the value part is JSON:
jq -Rn '
reduce (inputs / "=") as [$key, $value] ({};
.[$key] = ($value | fromjson / " ")
)
' input.txt
Otherwise, just removing the first and last "
from it:
jq -Rn '
reduce (inputs / "=") as [$key, $value] ({};
.[$key] = ($value | ltrimstr("\"") | rtrimstr("\"") / " ")
)
' input.txt
The most robust approach, however, would be a regex matching, e.g. using capture
:
jq -Rn '
[inputs | capture("^(?<key>[^=] )=\"(?<value>.*)\"$") | .value /= " "]
| from_entries
' input.txt
Output:
{
"keya": [
"valuea",
"valueb"
],
"keyb": [],
"keyc": [
"valuex"
]
}