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

白昼怎懂夜的黑 提交于 2020-05-09 09:45:26

问题


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

]

回答1:


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.




回答2:


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: .}}


来源:https://stackoverflow.com/questions/51115902/convert-text-file-with-key-value-pair-to-specific-json-format-in-jq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!