简体   繁体   中英

jq parse json problem cant get it to cycle loop

$ cat sax.json 

{"sax": [{"name": "mex20", "links": {"self": "http://website/catalog/sax/e49887"}, "tags": null, "enabled": true, "id": "e49887", "description": null}, {"name": "mex15", "links": {"self": "http://website/catalog/sax/e6de26"}, "tags": null, "enabled": true, "id": "e6de26", "description": null}, {"name": "mex56", "links": {"self": "http://website/catalog/sax/6cc093"}, "tags": null, "enabled": true, "id": "6cc093", "description": null}, {"name": "mex82", "links": {"self": "http://website/catalog/sax/89e0fe"}, "tags": null, "enabled": true, "id": "89e0fe", "description": null}]}
$ cat sax.json | jq  '.sax[] | select(.name | contains("mex"))' | jq .id

"e49887"
"e6de26"
"6cc093"
"89e0fe"

get_id.sh

#!/bin/bash

declare -a array=($(jq .sax[].name sax.json ))

for i in "${array[@]}"
  do  cat sax.json | jq '.sax[] | select(.name | contains($i))' | jq .id
done

cycle doesnt work. help please

  1. In the first query, there is no need to call jq twice; you can also avoid the UUOC:
< sax.json jq '.sax[] | select(.name | contains("mex")) | .id' 
  1. To make a shell variable's value available to jq, it is often best to use the --arg or --argjson command-line option. In your case, you'd want to use --argjson as $i already contains the enclosing quotation marks: jq --argjson i "$i"...

  2. Alternatively, you could set the array contents using jq -r to strip away the quotation marks, and then use --arg i "$i" .

  3. The semantics of contains is rather complex; in general, to check if one string is a substring of another, it is better to use startswith , index , test , or similar, as appropriate.

jq --argjson i "$i" 

So jq can't be used in loop? foreach?

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