placplacboom
placplacboom

Reputation: 899

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.

Upvotes: 1

Views: 1313

Answers (1)

pmf
pmf

Reputation: 36088

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"
  ]
}

Upvotes: 3

Related Questions