I receive a JSON response in an Ajax request from the server. This way it works:

{"a":"1","b":"hello‘kitty’"}

但我没有成功地在kitty左右加上双引号.

When I convert " to \x22 in the Ajax response, it is still interpreted as " by JavaScript and I cannot parse the JSON.

Should I also escape the \ and unescape later (which would be possible)?

How to do this?

Edit: I am not sure if i expressed it well: I want this string inside of "b" after the parse:

hello "kitty"

If necessary I could also add an additional step after the parse to convert "b", but I guess it is not necessary, there is a more elegant way so this happens automatically?

Edit2: The ajax page is generated by php. I tried several things now to create the value of b, all result in JSON parse error on the page:

  $b = 'hello "kitty"';      

  // no 1:
  //$b = str_replace('"',"\x22",$b);

  // or no 2:
  // $b = addslashes($b);  

  // or no 3: 
  $b = str_replace('"','\"',$b);

  echo '{ "a" : "1", "b" : "' . $b . '"}';

Edit3:此解决方案最终有效:

$b = 'hello "kitty"';      
$b = str_replace('"','\\"',$b); 
echo '{ "a" : "1", "b" : "' . $b . '"}';

推荐答案

Just escape it with a backslash:

> JSON.stringify({"a": 5, "b": 'a "kitty" mighty odd'})
{"a":5,"b":"a \"kitty\" mighty odd"}
> JSON.parse('{"a":5,"b":"a \\"kitty\\" mighty odd"}')
Object
  a: 5
  b: a "kitty" mighty odd
  __proto__: Object

JSON parsers recognize \" inside double-quoted strings as a double quote. Note that in the second example, the double-backslash is needed because there's a Javascript parser pass, then another JSON parser pass.

Json相关问答推荐

将JSON数组组织到菜单中

根据值过滤输入的JSON并使用它准备预期的输出

Delphi 11.3无法从变体创建/添加JSON

使用 Groovy 将 XML 转换为 JSON

如何使用 serde_json 构建有状态的流式解析器?

使用 jq 和 awk 拆分大型 JSON 文件

Powershell - 如何从 JSON 中删除/过滤元素但保留其余部分?

使用带有逗号的字段名称构建 struct

使用 BASH 和 JQ 我想将 json 文件与 bash 数组进行比较

使用 Ansible 解析来自 Juniper 交换机的 JSON 输出

Golang / Go - 如果 struct 没有字段,如何将其编组为空?

Swift - 将图像从 URL 写入本地文件

如何找出实际安装了哪个版本的 bower 包?

JSON RPC - 什么是id?

应该使用什么标头将 GZIP 压缩 JSON 从 Android 客户端发送到服务器?

json.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)

如何使用 jq 将 JSON 对象流转换为数组

JSON 语法错误:'unexpected number' 或 'JSON.parse: expected ',' or '}' after property value in object'

使用 jq 从 bash 中管道分隔的键和值创建 JSON

我应该如何处理 JSON 中的 HATEOAS 链接和引用?