首页 > 解决方案 > 尝试解析字符串化的 quill.js quill 时出现 Javascript JSON.parse() 错误

问题描述

我正在尝试使用 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

Edit2:来自源的行与另一个产生相同错误的字符串

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

标签: javascriptjsonejsquill

解决方案


data.toString()会回来"[Object object]"的,所以这就是你将得到的一切resolve。你应该打电话给stringify那里,这可能会有所帮助。


推荐阅读