Parse json and choose items\keys upon condition

 ̄綄美尐妖づ 提交于 2019-12-24 11:28:04

问题


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


回答1:


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




回答2:


If it is from an AJAX, you don't need to parse the response.

$.get('api_url', function(response) {
    response.forEach(function (key, value) {
        if (value.item1 == true) {
            console.log(value.item2)
            // Do your thing here
        }
    }
}



回答3:


it seems to work with the following jq line:

jq 'map(select(.item1 == true)) | .[].item2'


来源:https://stackoverflow.com/questions/31533719/parse-json-and-choose-items-keys-upon-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!