简体   繁体   English

如何检查json文件是否具有特定元素?

[英]How to check if the json file has a specific element?

How to check if ["foo"]["bar"] is present in a json file from BASH script? 如何检查BASH脚本的json文件中是否存在[“ foo”] [“ bar”]? tried below: 尝试以下:

$ cat myJson.json | if ( python3 -c "import sys,json; json.load(sys.stdin)['foo']['bar']"); then echo "found foo-bar"; fi
$ found foo-bar

it works, but it prints below if the element is not present: 它可以工作,但是如果不存在该元素,则会在下面打印:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
KeyError: 'baz'

but bash script don't fail anyway. 但是bash脚本无论如何都不会失败。

Update: 更新:

Tried try-except: 尝试过以下尝试:

cat myJson.json | \
if (
python3 -c "
import sys,json
try:
   json.load(sys.stdin)['foo']['bar']
except KeyError:
   #exit with non-0.
   sys.exit(1)
") then echo "found foo_bar"; FOUND_FOO_BAR=true;
fi
echo $FOUND_FOO_BAR
$ found foo_bar
$ 
$

I am expecting "true" to be printed after `found foo_bar', but it doesn't, what am I doing wrong? 我期望在“找到foo_bar”之后打印“ true”,但是没有,我在做什么错?

您可以使用jq工具:

jq 'map(has("foo.bar"))' myJson.json && echo "found foo-bar"

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

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