将 String 转换为 Json 以应用 JSON Patch

Rah*_*ani 5 javascript json node.js express

我正在尝试使用 postmon 获取 json 字符串的请求来应用 json 补丁。问题是我无法将字符串转换为 json,数据是通过变量发布的。每次我这样做

JSON.parse(document);
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

SyntaxError: Unexpected token ' in JSON at position 1
Run Code Online (Sandbox Code Playgroud)

我发送的数据如下

{"document":"{'baz': 'qux', 'foo': 'bar'}"}
Run Code Online (Sandbox Code Playgroud)

通过邮递员使用 post 方法。

我正在使用 req.body 来获取发布数据

小智 0

"{'baz': 'qux', 'foo': 'bar'}" is not a valid json string.
Run Code Online (Sandbox Code Playgroud)

单引号的 json 格式不正确,因此解析器不会接受单引号并会抛出以下错误

SyntaxError:JSON 中位置 1 处出现意外标记 '

在此输入图像描述

因此,为了能够将该字符串解析为 json,您需要在解析之前使用 str.replace() 将 ' 引号替换为 " 引号

演示:

"{'baz': 'qux', 'foo': 'bar'}" is not a valid json string.
Run Code Online (Sandbox Code Playgroud)