简体   繁体   English

使用jq在数组Json中选择值

[英]Select value in array Json using jq

I have one json file. 我有一个json文件。

{
"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. 我希望使用jq实现。 Please help. 请帮忙。

With this filter in the file cars.jq: 在文件cars.jq中使用此过滤器:

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

and your JSON in cars.json, the invocation: 以及您在cars.json中的JSON,调用:

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. 当然,还有许多其他方法可以将模型名称传递给jq程序。

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>' 语法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. 我不知道您为什么要要求jq。 In plain vanilla Javascript, the solution is very simple. 在普通的Javascript中,解决方案非常简单。 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". 在这里,我已经在函数调用中对模型“ Focus”进行了硬编码,这将返回名称“ 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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