“减少输入"中的可选元素包括:条款 [英] Optional element in "reduce inputs" clause
问题描述
我正在研究我从先前的问题中得到的出色的答案.
I am working on this excellent answer that I got from an earlier question.
这是我目前拥有的:
function data {
cat <<EOF
Security:ClientId=123456
Security:ClientSecret=abcdefg
AppSettings:Environment=Dev
AnotherCustomSetting=SomethingElse
EOF
}
data | jq -nR '
def parse: capture("(?:(?<group>[^:=]*):)?(?<property>[^=]*)=(?<value>.*)");
reduce inputs as $line ({};
($line | parse) as $envVar
| if .[$envVar.group] != null then .[$envVar.group][$envVar.property] = ($envVar.value) else .[$envVar.property] = ($envVar.value) end)
'
我的最终目标是拥有一个像这样的Json文件:
My end goal is to have a Json file like this:
{
"Security": {
"ClientId": "123456",
"ClientSecret": "abcdefg"
},
"AppSettings": {
"Environment": "Dev"
},
"AnotherCustomSetting": "SomethingElse"
}
在上一个问题中,我没有指出我需要在根级别使用属性(在这种情况下,为 AnotherCustomSetting
).
In my previous question I did not indicate that I would need properties at the root level (AnotherCustomSetting
in this case).
为了尝试使根级别属性起作用,我将RegEx修改为具有一个可选组,但是原始答案的 reduce输入
并不认为 group
为空(并以null错误失败).因此,我尝试在减少输入
部分中放置 if
语句.不幸的是,它失败并显示以下错误:
To try to get root level properties working, I modified the RegEx to have an optional group, but the original answer's reduce inputs
did not anticipate the group
being null (and failed with a null error when it was). So I attempted to put an if
statement in the reduce inputs
section. Unfortunately it is failing with the following error:
jq:错误(在4处):无法为空索引对象
jq: error (at :4): Cannot index object with null
是否有可能像我尝试的那样在减少输入
部分中执行 if if else else
?如果是这样,怎么做?
Is it possible to do an if then else
in a reduce inputs
section like I am attempting? If so, how is it done?
推荐答案
这应该做到:
def parse: capture("(?<x>[^:=]*)(:(?<y>[^:=]*))?=(?<value>.*)");
reduce inputs as $line ({};
($line | parse) as $p
| if $p.y then .[$p.x][$p.y] = $p.value
else .[$p.x] = $p.value end )
当然可以进一步加强...
Of course this could be further robustified...
这篇关于“减少输入"中的可选元素包括:条款的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!