将具有key = value对的文本文件转换为jq中的特定json格式 [英] Convert text file with key=value pair to specific json format in jq

查看:224
本文介绍了将具有key = value对的文本文件转换为jq中的特定json格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含以下值 input.txt

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

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

需要jq rexpression通过同时删除"\ r"将其转换为json格式以下

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

output.json

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

并获得以下输出

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

]

推荐答案

jq 解决方案:

jq solution:

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

输出:

{
  "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.

这篇关于将具有key = value对的文本文件转换为jq中的特定json格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆