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"
}
]
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"
}
}
}
This solution assumes =
does not appear in the "value" section of the input strings.
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: .}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With