Reputation: 15
Here is my JSON file
{
"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": []
}
]
}
]
}
and my output has to be:
[{"name":"Joe _ item1","code": }]
[{"name":"Joe _ item2","code": }]
[{"name":"Jim _ item3","code":gst-70}]
[{"name":"Jim _ item4","code":gst-50}]
I am trying to achieve it through jq, however the null event values make it very complex and unable to achieve the output as above. Can this be done using jq? Here is my code:
.item[]
| ("[{\"name\":\"" + .name + " _ " + .item[].name1+",\"code\":") ,
(.item[]?.event[]?.script.exec[0] + "}]" )
Upvotes: 1
Views: 192
Reputation: 116650
The requirements are not very clear in several respects, but the following is probably close to what you have in mind. The output, however, is valid JSON.
.item[]
| .name as $name
| .item[]
| {name: "\($name) _ \(.name1)",
code: (if .event then .event[].script.exec[0]|split("=")[1]
else null end) }
With your input, this produces:
{"name":"Joe _ item1","code":null}
{"name":"Joe _ item2","code":null}
{"name":"Jim _ item3","code":"gst-70"}
{"name":"Jim _ item4","code":"gst-50"}
You might want to obtain the substring of interest in some other way, e.g.:
.[1+index("="):]
or:
sub("^[^=]*="; "")
Upvotes: 1