JSON.parse得到“未捕获的SyntaxError:意外的令牌h"; [英] JSON.parse get "Uncaught SyntaxError: Unexpected token h"

查看:76
本文介绍了JSON.parse得到“未捕获的SyntaxError:意外的令牌h";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试传递以下字符串时出现语法错误:

I get the syntax error when I try to pass the following string:

JSON.parse("[{\"Date\": \"4/4/2016 4:15:19 PM\", \"Message\":\"<h3>New 
Message</h3> Generated at 4/4/2016 4:15:19 PM.<br/><br/>Heavy Responsive 
URL: <a href=\"https://performingarts.withgoogle.com/en_us\" ></a><br/><br/>
<img src=\"https://s-media-cache-ak0.pinimg.com/236x/06/bd/ac/06bdacc904c12abdce3381ba1404fd7e.jpg\" /> \"} ]");

我知道当我使用双引号时,错误来自链接.

I know that the error come from the link when I use double quote.

如果我使用单引号,则没有问题,但是数据是从服务器端获取的,我无法控制要传入的内容,因此只能在我这一边进行控制.

If I use single quote then no issue, but the data is getting from server side, I got no control over what going to pass in so I can only control on my side.

到目前为止,我从互联网上阅读的内容都尝试了以下操作:

From what I read from the internet so far, I tried the following:

  1. 首先使用JSON.stringify,然后仅使用JSON.parse.我可以解析 没问题,但是当我尝试循环数据时会出现问题.反而 将其循环为JSON,循环将数据作为字符串并循环 每个文本.

  1. Use JSON.stringify first, then only use JSON.parse. I can parse with no issue but problem occur when I try to loop the data. Instead of looping it as JSON, the loop take the data as string and loop every single text.

转义我当前正在执行的每个双引号,但不是 如上所示工作.但是如果我将每个双引号替换为 字面意思是,恐怕有些消息可能是双重的 报价也将变成文字,这将导致怪异 消息.

Escape every double quote which I'm currently doing, but it's not working as shown above. But if I replace every double quote to literal, I'm afraid some of the message that suppose to be double quote will turn into literal as well, which will result in weird looking message.

请告知我还有什么其他替代方法可以解决这个问题.

Please advice what other alternative I have to solve this.

推荐答案

您已将JSON嵌入到JavaScript字符串文字中.

You have JSON embedded in a JavaScript string literal.

"\是JSON中的特殊字符,也是JavaScript字符串文字中的特殊字符.

" and \ are special characters in JSON and are also special characters in a JavaScript string literal.

href=\"https:在JavaScript字符串文字中转义".然后,它在JSON中成为".这会导致错误.

href=\"https: escapes the " in the JavaScript string literal. It then becomes a " in the JSON. That causes an error.

当您希望"作为JSON中的数据时,您必须:

When you want the " as data in the JSON you must:

  • "进行JavaScript转义(就像您已经做的那样)
  • 通过添加\
  • 对JSON的"进行转义.
  • 转义\ for JavaScript
  • Escape the " for JavaScript (as you are doing already)
  • Escape the " for JSON by adding a \.
  • Escape the \ for JavaScript

href=\\\"https:

这篇关于JSON.parse得到“未捕获的SyntaxError:意外的令牌h";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆