解析json并根据条件选择项目 [英] Parse json and choose items\keys upon condition
问题描述
我正在尝试解析从某个REST API获取的json文件。
json有几个数组,我想根据另一个项的值从数组中选择一个特定项。
例如:
[
{
item1:true,
item2:value
},
{
item1:false,
item2:value
}
]
我想检查item1是否为真,只有这样,我才想从item2获取值。
我该如何处理?
我试过使用一个名为下划线的json解析器,这很棒,但我无法得到最终结果。
谢谢
首先你需要解析:
var objJSON = JSON.parse(yourJsontext);
并检查条件
if(objJSON [0] .item1 ===true){
}
对于使用 jq 的shell脚本,请将您的json复制到test.json:
jq'。[0] .item1'test.json
您可以在 jqplay 上试用它/ p>
输入您的json并输入。[0] .item1作为过滤器
I'm trying to parse a json file that I get from a certain REST API. The json has a few arrays, and I'd like to choose a specific item from an array based on the value of another item.
for example:
[
{
"item1": true,
"item2": "value"
},
{
"item1": false,
"item2": "value"
}
]
I'd like to check if item1 is true, and only then, i want to get the value from item2.
how would I handle it? I've tried to use a json parser named underscore which is great, but I cant get to the final result.
thanks
First you need to parse:
var objJSON = JSON.parse(yourJsontext);
And check for the condition
if( objJSON[0].item1 === "true"){
}
For shell scripting using jq, copy your json to test.json:
jq '.[0].item1' test.json
You try it on jqplay
enter your json and enter ".[0].item1" as filter
这篇关于解析json并根据条件选择项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!