我有一个 JSON 文件,其中包含彼此相似但不相同的对象。所有对象都有一个主标识符,但对象内可能存在也可能不存在其他键。
我的问题:对于对象中的给定键,如果存在,如何打印出该值,如果不存在,如何打印出类似“NA”的内容,无论哪种方式都打印该键的原始名称?
输入示例:
{
"DBInstances": [
{
"Identifier": 101,
"foo": "some_value",
"bar": 60,
"Model": "A"
},
{
"Identifier": 102,
"foo": "some_value",
"Model": "B"
}
]
}
Run Code Online (Sandbox Code Playgroud)
期望的输出:
{
"Identifier": 101,
"foo": "some_value",
"bar": 60,
"Model": "A"
},
{
"Identifier": 102,
"foo": "some_value",
"bar": "NA",
"Model": "B"
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个函数,它(部分)适用于不存在,但根本不适用于存在:
def exist(element):
if (has( element ) == true)
then { element: "true" }
else { element: "NA" }
end;
Run Code Online (Sandbox Code Playgroud)
当我用以下方式调用它时:
exist( "bar" )
Run Code Online (Sandbox Code Playgroud)
“存在”部分是完全错误的,因为 JQ 打印“element”和“true”而不是原始键名称和值。
对于“不存在”的部分,JQ 打印“NA”就可以了,但是“element”而不是原始的键名称。
我正在使用 JQ …
MySQL允许在my.cnf文件中将参数SQL_MODE设置为多个值。我如何在Amazon RDS上做同样的事情?
更新:此问题已得到解决...请参阅下文。
我的老板希望我们的团队使用JQ解析JSON文件。我使用的应用会生成需要转换的JSON。我有一个看起来像这样的文件:
{
"Collections": [
{
"OptionGroups": [
{
"OptionGroupName": "Test1",
"Status": "in-sync"
}
],
"Version": "3.4.25",
"InstanceIdentifier": "Dev1"
},
{
"OptionGroups": [
{
"OptionGroupName": "Test2",
"Status": "in-sync"
}
],
"Version": "3.4.22",
"InstanceIdentifier": "Dev2"
}
]
}
Run Code Online (Sandbox Code Playgroud)
执行此操作时,使用JQ:
cat json.txt | jq -r '.Collections[].OptionGroups[].OptionGroupName, .Collections[].InstanceIdentifier, .Collections[].Version'
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
Test1
Test2
Dev1
Dev2
3.4.25
3.4.22
Run Code Online (Sandbox Code Playgroud)
我如何获得看起来像这样的输出:
Test1 Dev1 3.4.25
Test2 Dev2 3.4.22
Run Code Online (Sandbox Code Playgroud) 我有一个JSON文件:
{
"ClassIdentifier": "consumer-leads",
"StateMode": "txt-2300",
"StateGroups": []
}
{
"ClassIdentifier": "main",
"StateMode": null,
"StateGroups": [
{
"Status": "active",
"StateGroupName": "default"
},
{
"Status": "active",
"StateGroupName": "brown-space"
},
{
"Status": "active",
"StateGroupName": "txt-hosts"
}
]
}
{
"ClassIdentifier": "paid-media",
"StateMode": "txt-2300",
"StateGroups": []
}
{
"ClassIdentifier": "reports",
"StateMode": null,
"StateGroups": [
{
"Status": "active",
"StateGroupName": "txt-hosts"
},
{
"Status": "active",
"StateGroupName": "grey-space"
},
{
"Status": "active",
"StateGroupName": "default"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我需要的输出:
consumer-leads,txt-2300,null
main,null,brown-space|default|txt-hosts
paid-media,txt-2300,null
reports,null,default|grey-space|txt-hosts
Run Code Online (Sandbox Code Playgroud)
请注意,StateGroups(如果它们一直存在)按StateGroupName排序为(或之前)它们被转换为由竖线分隔的值字符串.
我所尝试的已经给了我部分结果,但没有真正的工作:
cat json_file …Run Code Online (Sandbox Code Playgroud)