我必须使用 JSON 有效负载向某个服务发送 POST 请求,其中包含一些用户输入。该输入变量需要进行 JSON 编码以防止注入攻击。
发送请求并将响应 JSON 解析为 RESP 变量的代码示例:
RESP=`curl --connect-timeout "10" -s -H "Content-Type: application/json" \
-X POST -d '{ "Attribute": '"'$USERINPUT'" }',\
$ENDPOINT | $JQ -r '.key'`
Run Code Online (Sandbox Code Playgroud)
$USERINPUT在创建 JSON 有效负载之前如何清理或 JSON 编码?
使用该jo实用程序,可以使用
data=$( jo Attribute="$USERINPUT" )
Run Code Online (Sandbox Code Playgroud)
然后您将使用-d "$data"withcurl将其传递到终点。
旧的(但仍然有效)答案使用jq而不是jo:
使用jq:
USERINPUT=$'a e""R<*&\04\n\thello!\''
Run Code Online (Sandbox Code Playgroud)
这个字符串有几个双引号、一个 EOT 字符、一个换行符、一个制表符和一个单引号,以及一些普通的文本。
data="$( jq --null-input --compact-output --arg str "$USERINPUT" '{"Attribute": $str}' )"
Run Code Online (Sandbox Code Playgroud)
这会构建一个 JSON 对象,其中包含用户数据作为单独Attribute字段的值。
使用短选项同样的事情:
data="$( jq -nc --arg str "$USERINPUT" '{"Attribute": $str}' )"
Run Code Online (Sandbox Code Playgroud)
由此我们得到
{"Attribute":"ae\"\"R<*&\u0004\n\thello!'"}
Run Code Online (Sandbox Code Playgroud)
作为 中的值$data。
现在可以在您的呼叫中使用它curl:
RESP="$( curl --connect-timeout "10" -s \
-H "Content-Type: application/json" \
-X POST -d "$data" \
"$ENDPOINT" | jq -r '.key' )"
Run Code Online (Sandbox Code Playgroud)
小智 0
您可以从命令行使用 Python 模块 json.tool 来解析 JSON:
export USERINPUT="[1,2,3]"
echo $USERINPUT| python -mjson.tool
[
1,
2,
3
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10701 次 |
| 最近记录: |