special char in JSON

谁说我不能喝 提交于 2019-12-12 05:24:52

问题


I should send Hi" to a Yahoo server, so in PHP I should place \ befor the ", but it will get bad JSON arguments. How should I do it?

Place Hi" in JSON code without error?

$message = "Hi\"";
$postdata = '{
             "message" : "'.$message.'"
             }';

回答1:


Use json_encode instead of hand-crafting JSON:

$postdata = json_encode(array("message" => $message));

If you must handcraft your JSON, don't forget to add a backslash before a quotation mark:

$message = "Hi\\\"";
// or, more clearly ...
$message = 'Hi\\"';



回答2:


New line character will not work in case of Tooltip with some browsers.
Not working \r\n or \n
Not working single quotes \'abcd

Use double backslash to escape characters.

Solution : use '\\\r\\\n' in place of '\r\n' ,
it will solve your problem.
Happy coding...!



来源:https://stackoverflow.com/questions/7283314/special-char-in-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!