使用 python mjson.tool 在 Bash 中解码 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17375940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:48:35  来源:igfitidea点击:

Decode JSON in Bash using python mjson.tool

pythonjsonbashgrep

提问by Justin

I need to get a keyfrom JSON in standard bash, and found the following:

我需要key在标准 bash 中从 JSON获取 a ,并发现以下内容:

echo '{"first_key": "value", "second_key": "value2"}' | python -mjson.tool | grep 'first_key'

But this returns:

但这会返回:

"first_key": "value",

How can I just return value, i.e. not the key, and remove the quotes and comma.

我怎么能只返回value,即不是键,并删除引号和逗号。

Thanks.

谢谢。

回答by Ignacio Vazquez-Abrams

$ echo '{"first_key": "value", "second_key": "value2"}' | python -c 'import sys, json; print json.load(sys.stdin)[sys.argv[1]]' first_key
value

回答by jaypal singh

Since you tagged it grephere is a solution for that (though Ignacio'ssolution is the right way to do it):

由于您grep在此处标记了它,因此这是一个解决方案(尽管Ignacio 的解决方案是正确的方法):

echo "..." | grep -oP "(?<=\"first_key\": \")[^\"]+"

Output:

输出:

$ echo '{"first_key": "value", "second_key": "value2"}' | grep -oP "(?<=\"first_key\": \")[^\"]+"
value