Json解析遭遇回车符

阅读更多
其实这个问题我自己从来没遇到过。 是公司里的其他同事提的,还要求客户不能输入回车键……

这个是把json当普通字符串解析出现的问题, 可以用下面的方法解决:
newJson=JSON.parse(jsonStringWithCR.replace(/\n/g, '\\n').replace(/\r/g,'\\r'))


但我认为, 就同事的情况而言,是因为他们把后端传过来json当成字符串来接收造成的,如果直接接收以json就不会遇到这种情况的。

Hi xxx,
below is my test result, may it could help you:
send: {"note":"A\r\nB\r\nC"}  // it is a json, not jsonString
receive: '{"note":"A\r\nB\r\nC"}'  // this is an error receive,regard json as a plain string, correct jsonString shoud be '{"note":"A\\r\\nB\\r\\nC"}'

// so we need revise it before we want to parse it to json:
    correctJsonString = errorJsonString.replace(/\r/g, '\\r').replace(/\n/g,'\\n')
    newJson=JSON.parse(correctJsonString)  
	
// of course a better approach is receive as a json, rather than a String

你可能感兴趣的:(Json解析遭遇回车符)