在JavaScript中如何将JSON对象转为字符串赋值给对象属性?
解决JavaScript中JSON对象转字符串赋值给对象属性的问题
嘿,我一眼就瞅到你代码里的小问题啦——你在定义container_list的时候,提前引用了还没声明的formatted_content,而且const声明的变量有「暂时性死区」的特性,这肯定会触发报错的。让我给你修正并掰扯清楚:
问题根源
你把formatted_content的定义放在了container_list之后,但const声明的变量不会被提升到作用域顶部。当代码执行到JSON.stringify(formatted_content)这一行时,formatted_content还处于未初始化的状态,浏览器会直接抛出ReferenceError。
修正后的代码
只需要把formatted_content的定义移到container_list前面,就能正常运行了:
// 先定义富文本内容的JSON对象 const formatted_content = { "ops": [ {"attributes":{"italic":true,"bold":true},"insert":"let's"}, {"insert":" write "}, {"attributes":{"underline":true},"insert":"something"}, {"insert":",需准确识别代码中富文本格式、特殊字符及数学公式类内容。"} ] }; // 再创建容器列表,此时JSON.stringify能正确获取到目标值 var container_list = [ {type: 'editor', id: 't1', placeholder: 'first section'}, {type: 'onlytext', value: 'second section - only text'}, {type: 'editor', id: 't2', placeholder: 'third section'}, {type: 'editor', id: 't3', placeholder: 'fourth section', defvalue: JSON.stringify(formatted_content)} ];
额外补充
JSON.stringify()会自动处理对象里的特殊字符(比如中文、标点)和嵌套结构,转成合法的JSON字符串,完全不用担心富文本格式、特殊字符的识别问题。- 如果后续需要把
defvalue的字符串转回JSON对象,直接用JSON.parse(container_list[3].defvalue)就能搞定。
内容的提问来源于stack exchange,提问作者inspiral
相关产品推荐
相关产品推荐

