duanha3539 2014-07-08 19:32
浏览 98

在javascript中使用PHP生成的JSON:反斜杠问题

I have seen a few relevant answers where a specific character in JSON string from PHP is converted to javascript friendly version. With some help I have come this far :

  • Javascript does not handle backslashes very well, infact these need to be replaced by double backslash.
  • New line characters do not work well, either you need a carriage return or remove the symbols totally.
  • double quotes in strings need escaping by 'double backslash' instead of single one.
  • forward slash which appears escaped by backslash in paths does not need escaping.

example non-working json below (validated at jsonlint but fails in JSON.parse)

["string
 next line \"quoted text\" and \b at path \/var\/opt "]

I needed to convert to following after replacements to make it work

["string next line \\"quoted text\\" and \\b at path /var/opt "]

The Problem

My problem is that my json in php depends on user input and I don't know what they will put up. PHP will use the standard json conversion method and have its validation.

Like the above, are there any other scenarios I should be covering, specifically unicode , other special characters etc ?

Update

My json string is a bit more complex than this example and changes dynamically, a small example is

{ "settings.conf": [ "tooltip='dynamic unicode text multiline with \ or \\ or even \" etc '", "value=the value"]}

Im doing

var jstring = <?php sanitize_json(json_encode($source_array)); ?>

JSON.parse(jstring);

and my sanitize_json function is currently doing the backslash replacement and is working, however I want to include the newline characters . Also need to ensure there are no other issues of this kind with json in js.

  • 写回答

2条回答 默认 最新

  • drurhg37071 2014-07-08 19:51
    关注

    If you see the json_encode() documentation you will see there are various flags that you can set that will sanitise the data. In your case, JSON_UNESCAPED_SLASHES might do the trick:

    json_encode($data, JSON_UNESCAPED_SLASHES);

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题