【发布时间】:2020-10-06 22:20:24
【问题描述】:
我正在尝试使用 ejs 向客户端发送一些对象。 至少到目前为止,我这样做时没有遇到任何问题。 我这样存放羽毛笔
{"form_type":"blog","form_sub_type":"create","blog_title":"Test","quill_0":"{\"ops\":[{\"insert\":\"tesarfd\\n\"}]}"}
当我尝试先将它们发送给客户端时,我会运行此函数以从文件中获取对象
const fileToJson = async (filePath) => {
return new Promise(resolve => {
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
console.log(err);
resolve(false);
}
resolve(data);//returns json string
})
})
}
在客户端, 我尝试使用以下内容:
'<%-JSON.stringify(blog)%>'
'<%-blog%>'
当我记录第二个时,我只得到 [Object object] 并且无法访问它的字段。 当我登录我得到的第一个时:
{"edit":true,"editable":true,"blog_id":3,"blog":{"form_type":"blog","form_sub_type":"create","blog_title":"Test","quill_0":"{"ops":[{"insert":"tesarfd\n"}]}"}}
无法解析。
产生错误的代码:
const blog_info = '<%-JSON.stringify(blog)%>';
console.log(JSON.parse(blog_info));
错误:
Uncaught SyntaxError: Unexpected token f in JSON at position 51
at JSON.parse (<anonymous>)
at blog_panel?id=6:335
编辑2: 来自源代码的行与另一个产生相同错误的字符串
const blog_content=JSON.parse('{"edit":true,"editable":true,"blog_id":7,"blog":"{\"form_type\":\"blog\",\"form_sub_type\":\"create\",\"blog_title\":\"Test\",\"quill_0\":\"\\\"<p>Test</p>\\\"\"}"}');
JSON.parse() 抛出:
Uncaught SyntaxError: Unexpected token o in JSON at position 3
at JSON.parse (<anonymous>)
at blog_panel?id=6:335
【问题讨论】:
-
我觉得这个问题有点令人困惑。问题的标题是 "JSON.parse() error" 所以我认为它是关于
resolve(JSON.parse(data.toString()));行但是你没有提供错误是什么。您能否将您遇到的错误添加到问题中? -
@3limin4t0r 相应编辑
-
我只得到了[Object object],对吗?你期待它做什么? JSON.Parse 返回一个对象?!如果你想要一个字符串。不要解析它。
-
我正在尝试解析作为字符串传递给客户端的嵌套 json 对象
-
你快到了。查看您的“edit2”,您需要摆脱
JSON.parse(...)调用和周围的单引号。输出应该是const blog_content = {"edit":true, ...}
标签: javascript json ejs quill