如何从JSON字符串的参数中删除非文本字符、换行符、制表符等?

4
我有一些JSON字符串,其中可能包含\n\t,但我不想将它们保存到数据库中。使用strip_tags只能处理简单的字符串。我现在使用gsub(/(\\n)|(\\t)/, "")。 我想知道是否有其他Rails帮助器方法或更好的方法来实现这个功能。 例如:
"[{\"type\":\"checkbox-group\",\"label\":\"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\nFill in\\nthe Gap (Please\\nfill in the blank box with correct wor\",\"name\":\"checkbox-group-1527245153706\",\"values\":[{\"label\":\"Option 1\",\"value\":\"option-1\",\"selected\":true}]},{\"type\":\"text\",\"label\":\"\\n\\t\\t\\n\\t\\n\\t\\n\\t\\t\\n\\t\\t\\t\\n\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\t\\t\\tWhat are the unique features of\\ne-commerce, digital markets, and\\ndigital goods? \\n\\t\\t\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\",\"className\":\"form-control\",\"name\":\"text-1527245426509\",\"subtype\":\"text\"}]"

2
你能给我一个例子吗? - Kaushlendra Tomar
JSON字符串可能包含\n、\t,您想要删除格式还是数据中包含这些字符? - Stefan
@Sunny,我已经添加了我的JSON字符串示例参数。 - Pirun Seng
@Stefan 我想要移除那些字符。 - Pirun Seng
这些制表符和换行符最初从哪里来的? - Stefan
@Stefan,这是将来自Microsoft Office Word/PDF的文本复制并粘贴到formBuilder字段标签中的操作。 - Pirun Seng
2个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
4
你可以使用 squishsquish!
"  Some text \n\n and a tab \t\t with new line \n\n  ".squish
#=> "Some text and a tab with new line"
"Squish" 将去除文本两端的所有空白字符,并将剩余的空白字符(包括 \n\t 和空格)合并成一个空格。

1
FYI,“squish”等同于“str.gsub(/[[:space:]]+/, ' ').strip”。 - Stefan
@Deepak 在我的情况下,无论是squish还是squish!都没有帮助。 - Pirun Seng

2
我想这个可能会对你有帮助, JSON.parse(string).map{ |a| a['label'] = a['label'].squish; a}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,