Bash grep JSON响应
下面是一个文件中的JSON响应,即RGLogin.JSON 下面的grep命令可以检索会话\u id 但是下面的grep命令无法检索响应\u状态Bash grep JSON响应,json,bash,grep,jq,Json,Bash,Grep,Jq,下面是一个文件中的JSON响应,即RGLogin.JSON 下面的grep命令可以检索会话\u id 但是下面的grep命令无法检索响应\u状态 grep -m1 -oP '\s*"response_status"\s*:\s*"\K[^"]+' RGLogin.json 对于会话id,它正在查找引号。对于响应状态,不引用 grep -m1 -oP '\s*"response_status"\s*:\s*\K[^,]+' RGLogin.json 从思想上讲,解决此类问题的正确方法是使用
grep -m1 -oP '\s*"response_status"\s*:\s*"\K[^"]+' RGLogin.json
对于会话id,它正在查找引号。对于响应状态,不引用
grep -m1 -oP '\s*"response_status"\s*:\s*\K[^,]+' RGLogin.json
从思想上讲,解决此类问题的正确方法是使用了解数据格式的工具。也就是说,如果是JSON,那么必须使用JSON感知工具,并且对于线性/非嵌套数据结构,应该使用grep之类的行感知工具 例如,对于JSON结构,要使用用于JSON的walk path unix工具提取所需信息:
披露:除了@Dmitry的答案之外,我还是jtc工具的创建者 我总是使用php解释器来分析json数据。但是其他脚本语言也是可能的。下面是我的bash/php解决方案,用于获取这两个值:
#!/bin/bash
# define json string (get it from source)
json='{"response":{"session_id":"2d48cc11ceabf28c9e92f4b677337dcd"},"response_status":200,"response_details":null}'
# execute php script and eval the results
eval $( php <<- __EOT__
<?PHP
# php dollar sign must be escaped
\$data = json_decode('$json');
# print results in bash set-var format
printf("session_id=\"%s\"\nresponse_status=\"%s\"\n",
\$data->response->session_id,
\$data->response_status );
?>
# end-of-text marker must be placed at first column,
# or can be indented by real TABS (not SPACES).
__EOT__
)
# show params in bash
echo "session_id : $session_id"
echo "response_status : $response_status"
grep不是解析JSON的正确工具。改用:
此解决方案是特定于平台的。-P选项在BSD、macOS或任何其他非Linux操作系统上都不可用。
grep -m1 -oP '\s*"response_status"\s*:\s*\K[^,]+' RGLogin.json
bash $ <RGLogin.json jtc -w'[response_status]'
200
bash $
#!/bin/bash
# define json string (get it from source)
json='{"response":{"session_id":"2d48cc11ceabf28c9e92f4b677337dcd"},"response_status":200,"response_details":null}'
# execute php script and eval the results
eval $( php <<- __EOT__
<?PHP
# php dollar sign must be escaped
\$data = json_decode('$json');
# print results in bash set-var format
printf("session_id=\"%s\"\nresponse_status=\"%s\"\n",
\$data->response->session_id,
\$data->response_status );
?>
# end-of-text marker must be placed at first column,
# or can be indented by real TABS (not SPACES).
__EOT__
)
# show params in bash
echo "session_id : $session_id"
echo "response_status : $response_status"
session_id : 2d48cc11ceabf28c9e92f4b677337dcd
response_status : 200
$ jq -r '.response_status' RGLogin.json
200
$
$ jq -r '.response.session_id' RGLogin.json
2d48cc11ceabf28c9e92f4b677337dcd
$
$jq -r '.response.session_id, .response_status' RGLogin.json
2d48cc11ceabf28c9e92f4b677337dcd
200