简体   繁体   中英

Select value in array Json using jq

I have one json file.

{
"cars": 
[
    { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
    { "name":"BMW", "models":[ "320", "X3", "X5" ] },
    { "name":"Fiat", "models":[ "500", "Panda" ] }
]
}

I need to give one of the models as input and I want the corresponding name of the car will be the output.

Using jq, I wish to achieve. Please help.

With this filter in the file cars.jq:

.cars[]
| select(.models|index($model))
| .name

and your JSON in cars.json, the invocation:

jq --arg model Panda -f cars.jq cars.json

yields:

"Fiat"

Of course there are many other ways in which the model name can be passed in to the jq program.

As a one-liner:

jq --arg model Panda '.cars[] | select(.models|index($model)) | .name' cars.json

You can do something like this:

Syntax jq '.keyName<array/single value>'

cat file.json | jq '.cars[]' // retunts array of cars
cat file.json | jq '.cars[].name' // retunts list of names
cat file.json | jq '.cars[].models[]' // retunts array of car models

I don't know why you are requesting jq. In plain vanilla Javascript, the solution is very simple. I don't know if this is the most efficient way, but I would recommend a simple, easy to understand plain vanilla solution over anything else. Unless efficiency is an issue and a sufficiently more efficient solution can be found. Here, I've hardcoded the model "Focus" in the function call and this returns the name "Ford".

 <html> <head> <script> function getNameOfModel(model) { var nameOfModel = "Unknown"; var jsonData = {"cars": [ { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] }, { "name":"BMW", "models":[ "320", "X3", "X5" ] }, { "name":"Fiat", "models":[ "500", "Panda" ] } ]}; var jsonArray = jsonData["cars"]; var i = 0; while (i < jsonArray.length) { if (jsonArray[i]["models"].includes(model)) { nameOfModel = jsonArray[i]["name"]; i = jsonArray.length; } i++; } document.getElementById("carName").innerHTML = nameOfModel; } </script> </head> <body> <div><p id="carName"></p></div> <script>getNameOfModel("Focus");</script> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM