如何在单引号包裹的字符串中添加单引号?及JS提取JSON内容异常问题
我来帮你逐个解决这两个问题:
问题1:单引号包裹的字符串内部添加单引号的方法
这得看你用的是哪种编程语言,不过主流语言的解决思路大同小异,给你几个常用方案:
- 转义单引号:在字符串内部的单引号前加反斜杠
\,这样解释器就会把它当成普通字符而非字符串结束标记。
比如Python:
JavaScript:my_str = 'this is my string with a \'single quote\' inside' print(my_str) # 输出:this is my string with a 'single quote' insidelet myStr = 'this is my string with a \'single quote\' inside'; console.log(myStr); - 改用双引号包裹字符串:如果你的字符串里单引号比较多,直接用双引号把整个字符串包起来,内部的单引号就不需要转义了。
Python:
JavaScript:my_str = "this is my string with a 'single quote' inside"let myStr = "this is my string with a 'single quote' inside"; - 使用三引号(Python专属):Python里可以用三个连续的单引号包裹字符串,内部随便用单引号或者双引号都没问题:
my_str = '''this is my string with 'single quotes' and "double quotes" inside'''
问题2:JavaScript中JSON解析失败的问题
看你贴的这段代码,问题其实挺明显的,主要出在这两个地方:
- JSON不允许注释:你在第一个对象里加了
//testing this failed,这是JavaScript的注释语法,但JSON规范里完全不支持注释,这会直接导致解析失败。 - 存在无效的省略号和多余逗号:最后一个对象末尾的
...是无效的,而且前面的"size_y": 1,多了一个逗号(trailing comma),JSON也不允许这种语法。
先给你修正后的有效代码:
如果是直接定义JavaScript对象(不是JSON字符串),可以保留逗号但要去掉注释和省略号:
var items = [ { "html": "abc.jpg", "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 } ]; // 现在可以正常操作这个数组了,比如打印第一个元素的html属性 console.log(items[0].html); // 输出:abc.jpg
如果是要解析JSON字符串,那必须严格符合JSON规范,比如:
var jsonStr = `[ { "html": "abc.jpg", "col": 1, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "def.jpg", "col": 4, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "bac.jpg", "col": 6, "row": 1, "size_y": 2, "size_x": 2 }, { "html": "xyz.jpg", "col": 1, "row": 3, "size_y": 1, "size_x": 1 }, { "html": "Brand.jpg", "col": 4, "row": 3, "size_y": 1, "size_x": 1 } ]`; var items = JSON.parse(jsonStr); console.log(items); // 正常输出解析后的数组
总结一下:如果是写JavaScript对象字面量,注释和多余逗号(部分浏览器支持)可以灵活处理,但如果是JSON格式,必须严格遵守规范——不能有注释、不能有多余逗号、所有键必须用双引号包裹。
内容的提问来源于stack exchange,提问作者Rookie_123
相关产品推荐
相关产品推荐

