Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert text file with key=value pair to specific json format in jq

Tags:

json

shell

jq

I have a text file with following values in input.txt

key1=value1\r
key2=value2
key3=value3\r
key4=value4

need the jq rexpression to convert it to below json format by removing "\r" also

output.json

{
"Environment": {
    "Variables": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3",
        "key4": "value4"
    }
}

}

I have tried the below expression and getting the

jq -Rs [ split("\n")[] | select(length > 0) | split("=") | {(.[0]): .[1]} ] 

and getting the below output

[
  {
   "key1ey1": "Value1\r"
  },
  {
   "key2": "value2"
  },
  {
   "key3": "value3\r"
  },
  {
   "key4": "value4"
  }

]
like image 1000
user3323241 Avatar asked Sep 03 '25 09:09

user3323241


2 Answers

jq solution:

jq -sR '{"Environment":
            {"Variables": [split("\n")[:-1][] | rtrimstr("\\r") 
                             | split("=") | {(.[0]): .[1]}
                          ]  | add
            }
        }' input.txt

The output:

{
  "Environment": {
    "Variables": {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3",
      "key4": "value4"
    }
  }
}

Caveat

This solution assumes = does not appear in the "value" section of the input strings.

like image 116
RomanPerekhrest Avatar answered Sep 05 '25 00:09

RomanPerekhrest


The following approach allows = to appear in the value portion of the key=value strings:

Invocation: jq -n -R -f program.jq input.txt

program.jq:

[inputs | sub("\\\\r$";"") | capture("^(?<key>[^=]*)=(?<value>.*)")]
| from_entries
| {Environment: { Variables: .}}
like image 33
peak Avatar answered Sep 04 '25 23:09

peak