如何修复转义序列中反斜杠本身作为特殊字符的错误。通过bash脚本解析转义序列字符错误。
文件test.json
"specialties": {
"type": "array",
"description": "list of the provider's specialties",
"items": {
"type": "string",
"description": "A specialty of the provider provider's",
"nullable": true,
"example": "["Psychiatry"]"
}
}
我们正在尝试将此数据解析为具有以下代码的字符串。
data=$(cat test.json )
data=${data//"/\"}
data=$(echo "$data" | tr -d ' ')
echo $data
以上代码输出字符串
"specialties": { "type": "array", "description": "list of the provider's specialties", "items": { "type": "string", "description": "A specialty of the provider provider's", "nullable": true, "example": "[\"Psychiatry\"]" } }
下面的curl请求所使用的输出字符串抛出下面的错误
curl -s -H "Accept: application/json" -H "Content-Type: application/json" --location --request POST "${HOST}/api/v1/projects" --header "Authorization: Bearer "$token"" -d '{"name":"'${PROJECT_NAME}'","openText": '${data}',"source": "API"}'
{"timestamp":"2022-12-10T14:00:32.384+0000","status":400,"error":"Bad Request","message":"JSON parse error: Unexpected character ('P' (code 80)): was expecting comma to separate Object entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('P' (code 80)): was expecting comma to separate Object entriesn at [Source: (PushbackInputStream); line: 1, column: 34273]","path":"/api/v1/projects"}
我们使用这个(https://jsontostring.com/)网站将上面的json数据转换为字符串,它产生下面的输出字符串,这是与我们的Java应用程序工作。
""specialties":{"type":"array","description":"listoftheprovider'sspecialties","items":{"type":"string","description":"Aspecialtyoftheproviderprovider's","nullable":true,"example":"[\"Psychiatry\"]"}}"
两个输出字符串之间的区别是在单词"Psychiatry"的开头和结尾多一个反斜杠字符
#not working string part
"[\"Psychiatry\"]"
#working string part
"[\"Psychiatry\"]"
为什么在这种情况下会产生额外的反斜杠字符,以及如何获得该输出。
添加以下代码并使用jq工具后,现在已修复。谢谢fravadona。
data=$(cat test.json )
openText=$(echo $data | jq . -R | tr -d ' ')
echo $openText
#above code output string
""specialties":{"type":"array","description":"listoftheprovider'sspecialties","items":{"type":"string","description":"Aspecialtyoftheproviderprovider's","nullable":true,"example":"[\"Psychiatry\"]"}}"