我有一个像这样的 JSON 结构:
{
"objectSchema": {
"fields": {
"fieldArray": [
{
"a": "b",
"c": "d"
},
{
"x": 1,
"y": "z"
},
{
"x": 1,
"y": "z"
}
]
}
}
}
我现在的jq -
.objectSchema | def convertToSchema: if type == "array" then if length == 0 then {"type": "array", "items": {"type": "string"}} else {"type": "array", "items": (map(convertToSchema) | add)} end elif type == "object" then {"type": "object", "properties": (map_values(if type == "object" or type == "array" then convertToSchema else convertToSchema end))} elif type == "boolean" then {"type": "boolean"} elif type == "number" then {"type": "number"} elif type == "string" then {"type": "string"} elif type == "null" then {"type": "string"} else {"type": (type | tostring)} end; convertToSchema
我当前的输出/转换后的 JSON 模式 -
{
"type": "object",
"properties": {
"fields": {
"type": "object",
"properties": {
"fieldArray": {
"type": "array",
"items": {
"type": "object",
"properties": {
"x": {
"type": "number"
},
"y": {
"type": "string"
}
}
}
}
}
}
}
}
我想要的输出/JSON模式-
{
"type": "object",
"properties": {
"fields": {
"type": "object",
"properties": {
"fieldArray": {
"type": "array",
"items": {
"type": "object",
"properties": {
"a": {
"type": "string"
},
"c": {
"type": "string"
},
"x": {
"type": "number"
},
"y": {
"type": "string"
}
}
}
}
}
}
}
}
我当前的 jq 表达式仅将数组的最后一个字段转换为模式,而没有正确处理所有嵌套数组对象。
请给我一个正确的 jq 表达式,该表达式将处理所有 JSON 嵌套对象情况中的上述情况,并确保在应用 ConvertToSchema 函数之前考虑并正确合并数组中的每个项目,并创建一个包含所有项目的所有唯一属性的组合模式在数组中。
提供JQPlay链接以及正确的解决方案会更有帮助。
有一个简单但通用的“结构模式推理引擎” 在https://gist.github.com/pkoppstein/a5abb4ebef3b0f72a6ed(schema.jq)。 它产生一个与您描述的非常相似的模式(见下文), 但如果这不能直接接受,您可以添加一个过滤器 将其转换为您想要的形式,或调整 schema.jq 本身。
在密码(“.”)中使用 schema.jq,并使用您的文件作为 input.json:
< input.json jq 'include "schema" {search: "."}; schema'
产生:
{
"objectSchema": {
"fields": {
"fieldArray": [
{
"a": "string",
"c": "string",
"x": "number",
"y": "string"
}
]
}
}
}
备注:
include
语句。 但是,您可以通过编写如下内容来保持 schema.jq 不变:< input.json jaq -f <(cat schema.jq; echo schema)