Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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"
  ]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading