Use jq to read a file and build a json with data from file

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.

>Solution :

Assuming the value part is JSON:

jq -Rn '
  reduce (inputs / "=") as [$key, $value] ({};
    .[$key] = ($value | fromjson / " ")
  )
' input.txt

Demo

Otherwise, just removing the first and last " from it:

jq -Rn '
  reduce (inputs / "=") as [$key, $value] ({};
    .[$key] = ($value | ltrimstr("\"") | rtrimstr("\"") / " ")
  )
' input.txt

Demo

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

Demo

Output:

{
  "keya": [
    "valuea",
    "valueb"
  ],
  "keyb": [],
  "keyc": [
    "valuex"
  ]
}

Leave a Reply