这是我的JSON文件
{
"variables": [],
"item":[
{
"name": "Joe",
"item": [
{
"name1": "item1",
"request": {},
"response": []
},
{
"name1": "item2",
"request": {},
"response": []
}
]
},
{
"name": "Jim",
"item": [
{
"name1": "item3",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"//code=gst-70"
]
}
}
],
"request": {},
"response": []
},
{
"name1": "item4",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"//code=gst-50"
]
}
}
],
"request": {},
"response": []
}
]
}
]
}
我的输出必须是:
[{"name":"Joe _ item1","code": }]
[{"name":"Joe _ item2","code": }]
[{"name":"Jim _ item3","code":gst-70}]
[{"name":"Jim _ item4","code":gst-50}]
我试图通过jq实现它,但是null事件值使它非常复杂并且无法实现上述输出。可以使用jq完成吗? 这是我的代码:
.item[]
| ("[{\"name\":\"" + .name + " _ " + .item[].name1+",\"code\":") ,
(.item[]?.event[]?.script.exec[0] + "}]" )
答案 0 :(得分:1)
要求在几个方面并不十分清楚,但以下内容可能与您的想法非常接近。但是,输出是有效的JSON。
.item[]
| .name as $name
| .item[]
| {name: "\($name) _ \(.name1)",
code: (if .event then .event[].script.exec[0]|split("=")[1]
else null end) }
根据您的输入,这会产生:
{"name":"Joe _ item1","code":null}
{"name":"Joe _ item2","code":null}
{"name":"Jim _ item3","code":"gst-70"}
{"name":"Jim _ item4","code":"gst-50"}
您可能希望以其他方式获取感兴趣的子字符串,例如:
.[1+index("="):]
或:
sub("^[^=]*="; "")