bash 如何使用shell脚本从json字符串中grep特定字段值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39757409/
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 15:14:26  来源:igfitidea点击:

How to grep the specific field value from json string using shell script

jsonbashshell

提问by skumar

Below is my JSON string available in file, out of which I need to extract the value for statusin shell script.

下面是我在文件中可用的 JSON 字符串,我需要从中提取statusshell 脚本中的值。

Expected Output: status=success

预期输出: status=success

response.json

响应文件

{"eventDate":null,"dateProccessed":null,"fileName":null,"status":"success"}

Please let me know, if you need any information

如果您需要任何信息,请告诉我

回答by OrangesV

Look into jq. It is a very handy json parser.

调查一下jq。这是一个非常方便的 json 解析器。

If you want to extract just the status you can do something like:

如果您只想提取状态,您可以执行以下操作:

jq -r '.status' response.json

# output
success

You can format your output as well to follow the results you want.

您也可以格式化输出以遵循您想要的结果。

jq -r '"status=\(.status)"' response.json

# output
status=success

回答by hedleyyan

You can try sed:

你可以试试sed:

sed -n 's|.*"status":"\([^"]*\)".*|status=|p' response.json