Javascript 解析带逗号的字符串
Javascript parse a string with commas
我从我的 api 电话中得到这个字符串:
"{'attachments': [{'type': 'html', 'html': 'text-test'}, {'type': 'album', 'album': [{'url': 'htps://s3.eu-central-8f7ba8d118dbf1/pic/cdyegkwkaije7720e2f72.jpg', 'type': 'image'}]}]}"
我需要找到一种方法来解析它并能够遍历 attachments
列表中的项目,但是当我尝试 运行 JSON.parse(str)
时出现错误, 我猜是因为 attachments
这个词周围有逗号。
错误是Uncaught SyntaxError: Unexpected token ' in JSON at position 1 at JSON.parse
如何解码才能访问附件?
您必须将 ' 替换为 "。试试这个
var jsonStr ="{'attachments': [{'type': ..." //your api string
jsonStr = jsonStr.replaceAll("'","\"");
var result = JSON.parse(jsonStr);
JSON 需要 "
,而不是 '
。如果这是您自己的 API,您应该将实现更改为 return "
引用。如果您的 API 写成 JavaScript,最好使用 JSON.stringify(objectDataToSend)
。
如果这不是您自己的 API,我建议使用 String.replaceAll()
函数将所有 '
替换为 "
:
let data = "{'attachments': [{'type': 'html', 'html': 'text-test'}, {'type': 'album', 'album': [{'url': 'htps://s3.eu-central-8f7ba8d118dbf1/pic/cdyegkwkaije7720e2f72.jpg', 'type': 'image'}]}]}"
const result = JSON.parse(data.replaceAll("'", '"'));
我从我的 api 电话中得到这个字符串:
"{'attachments': [{'type': 'html', 'html': 'text-test'}, {'type': 'album', 'album': [{'url': 'htps://s3.eu-central-8f7ba8d118dbf1/pic/cdyegkwkaije7720e2f72.jpg', 'type': 'image'}]}]}"
我需要找到一种方法来解析它并能够遍历 attachments
列表中的项目,但是当我尝试 运行 JSON.parse(str)
时出现错误, 我猜是因为 attachments
这个词周围有逗号。
错误是Uncaught SyntaxError: Unexpected token ' in JSON at position 1 at JSON.parse
如何解码才能访问附件?
您必须将 ' 替换为 "。试试这个
var jsonStr ="{'attachments': [{'type': ..." //your api string
jsonStr = jsonStr.replaceAll("'","\"");
var result = JSON.parse(jsonStr);
JSON 需要 "
,而不是 '
。如果这是您自己的 API,您应该将实现更改为 return "
引用。如果您的 API 写成 JavaScript,最好使用 JSON.stringify(objectDataToSend)
。
如果这不是您自己的 API,我建议使用 String.replaceAll()
函数将所有 '
替换为 "
:
let data = "{'attachments': [{'type': 'html', 'html': 'text-test'}, {'type': 'album', 'album': [{'url': 'htps://s3.eu-central-8f7ba8d118dbf1/pic/cdyegkwkaije7720e2f72.jpg', 'type': 'image'}]}]}"
const result = JSON.parse(data.replaceAll("'", '"'));