首页 > 解决方案 > 如何在多行中编写单行字符串?

问题描述

我想通过 curl 发送一个带有长字符串字段的大 json,我应该如何将它裁剪为多行?例如:

curl -X POST 'localhost:3000/upload' \
  -H 'Content-Type: application/json'
  -d "{
    \"markdown\": \"# $TITLE\\n\\nsome content with multiple lines....\\n\\nsome content with multiple lines....\\n\\nsome content with multiple lines....\\n\\nsome content with multiple lines....\\n\\n\"
  }"

标签: bashshell

解决方案


您可以使用帖子中已有的技术将任何内容拆分为多行,方法是使用\. 如果您需要在带引号的字符串中间拆分,请终止引号并开始一个新的。例如,这些是等效的:

echo "foobar"
echo "foo""bar"
echo "foo"\
     "bar"

但是对于您的具体示例,我推荐一种更好的方法。在双引号字符串中创建 JSON 非常容易出错,因为必须转义所有内部双引号,这也变得难以阅读和维护。更好的选择是使用 here-document,将其通过管道传输到curl,并用于-d@-使其从标准输入读取 JSON。像这样:

formatJson() {
    cat << EOF
{
  "markdown": "some content with $variable in it"
}
EOF
}

formatJson | curl -X POST 'localhost:3000/upload' \
  -H 'Content-Type: application/json'
  -d@-

推荐阅读