Zoho Deluge集成QuickBooks API:换行符\n的兼容处理问题
问题描述
我使用Zoho Deluge脚本通过Rest API在QuickBooks中创建发票,遇到以下问题:Zoho中的行项目描述为多行格式,从Zoho获取行项目时,产品描述里的换行处会返回\n,但将该内容同步到QuickBooks时触发API错误。将\n替换为空格后,同步可正常进行,但我希望保留换行格式。
我尝试了以下代码:
LineDet.put("Description", item.get("product_description").replaceAll("\n", "\\\"\n"));
收到的API错误响应如下:
"Created Invoice":{ "Fault":{ "Error":[ { "Message":"Request has invalid or unsupported property", "Detail":"Property Name:Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value\n specified is unsupported or invalid", "code":"2010" } ], "type":"ValidationFault" }, "time":"2023-09-25T09:47:11.165-07:00" },
我的请求体示例:
{ "Line":[ { "DetailType":"SalesItemLineDetail", "Amount":189, "Description":"Color: Natural\nFront Side: Logo\nBack Side: None\n - Imprint: Full Color UV", "SalesItemLineDetail":{ "UnitPrice":1.89, "Qty":100, "ItemRef":{ "name":null, "value":"4" } } }, { "DetailType":"SalesItemLineDetail", "Amount":45, "Description":"Logo Set Up", "SalesItemLineDetail":{ "UnitPrice":45, "Qty":1, "ItemRef":{ "name":null, "value":"5" } } }, { "DetailType":"SalesItemLineDetail", "Amount":20, "Description":"Imprint Run Cost", "SalesItemLineDetail":{ "UnitPrice":0.2, "Qty":100, "ItemRef":{ "name":null, "value":"6" } } }, { "DetailType":"SalesItemLineDetail", "Amount":0, "Description":"Economy Shipping\n - Include Customer Packing Slip - \n\nShip 50pcs to x\nShip 50pcs to y", "SalesItemLineDetail":{ "UnitPrice":0, "Qty":1, "ItemRef":{ "name":null, "value":"7" } } }, { "DetailType":"SalesItemLineDetail", "Amount":45.5, "Description":"Factory Direct Drop Ship:", "SalesItemLineDetail":{ "UnitPrice":45.5, "Qty":1, "ItemRef":{ "name":null, "value":"8" } } } ], "CustomerRef":{ "value":"1" }, "DueDate":"2023-08-18", "CustomField":[ { "DefinitionId":1, "StringValue":"ECO09-145", "Type":"StringType", "Name":"Customer PO#" }, { "DefinitionId":2, "StringValue":"2023-08-18", "Type":"StringType", "Name":"Delivery Date" } ], "CustomerMemo":{ "value":"08.10.23 - Test PO ,09.21.223 - PO Generated" }, "Id":"35", "SyncToken":"4", "DocNumber":"N2230794-08" }
解决方法
错误根源是JSON格式不允许直接包含未转义的换行符(\n),必须将其转义为\\n,才能被JSON解析器正确识别。
- 修正转义代码:将
\n替换为\\n,修改后的Deluge代码如下:
LineDet.put("Description", item.get("product_description").replaceAll("\n", "\\\\n"));
解释:在Deluge字符串中,单个反斜杠需要用两个反斜杠(\\)表示,因此要生成JSON中的\n,需要写成\\\\n——最终发送的请求体中,换行符会被正确转义为\\n,符合JSON规范。
- 验证请求体格式:修改后生成的请求体中,Description字段的换行应呈现为
\\n,例如:
"Description":"Color: Natural\\nFront Side: Logo\\nBack Side: None\\n - Imprint: Full Color UV"
这样QuickBooks API就能正确解析该字段,不会触发非法字符错误。
- 备选方案:如果QuickBooks不支持描述字段显示换行,可将
\n替换为空格或<br>(若支持HTML格式),但转义换行符是保留多行格式的最优解。
内容的提问来源于stack exchange,提问作者Usama AHMED
相关产品推荐
相关产品推荐

