我注意到了一种我不想要的行为。我有一个<textarea>
,如果我可以输入一些文字,如下所示。
some content
some other content
yet another content
当我将此文本保存到JSON对象并存储它时,我得到的是:
"value" : "some content some other content yet another content"
或者,我有时会得到这个:
"value" : "some content
some other content
yet another content"
我猜我期待接收的内容是:
"value" : "some content \n
some other content \n
yet another content"
这样我就能以与输入内容相同的方式呈现内容。
但这似乎打破了我的JSON.parse(string)
。
我在 AngluarJS 中使用输入中的模型。
修改
答案 0 :(得分:1)
您可以尝试用其他内容替换换行符。
如果换行符会导致JSON.parse
出现问题,请尝试将其替换为<br/>
之类的其他内容,以便在检索数据时将其作为换行符。
在使用JSON.stringify
之前,您还可以尝试使用textarea
JSON.parse
,textarea
将document.getElementById("textarea-id").value.replace(/\n\r?/g, '<br />')
值转换为带有可见换行符的JSON字符串。
JSON.stringify(document.getElementById("textarea-id").value)
或强>
console.log
请参阅以下示例中的depends 'golang_app'
:
https://jsfiddle.net/fjj2psqj/1/
答案 1 :(得分:0)
// valid JSON
var data = {
"value": [
"line",
"line",
"line"
]
};
// stringify the data to save it as text
var dataString = JSON.stringify(data);
// parse the string and join the array to recover line breaks
// or iterate over values array depending on your use case
var withNewLines = JSON.parse(dataString).value.join("\n");
答案 2 :(得分:0)
您可以先将捕获的textarea字符串通过JSON.stringify运行,然后再将其发送到您的服务器,然后再在您的应用程序中再次使用JSON.parse。
$scope.doSomethingWithTextareaText = function() {
//assuming your textarea is bound to $scope.text
$scope.myObject['value'] = $scope.text;
$scope.myObject['stringifyValue'] = JSON.stringify($scope.text);
/*
$scope.myObject[value]:
some content
some other content
yet another content
$scope.myObject[stringifyValue]:
"some content\nsome other content\nyet another content"
JSON.parse($scope.myObject[stringifyValue]):
some content
some other content
yet another content
*/
}