Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript localStorage数据包含JSON数据。能修好吗?_Javascript_Json - Fatal编程技术网

Javascript localStorage数据包含JSON数据。能修好吗?

Javascript localStorage数据包含JSON数据。能修好吗?,javascript,json,Javascript,Json,我在一个网站上工作,跟踪用户点击的链接。数据以字符串形式存储在localStorage中。我知道localStorage中的字符串数据可以通过使用JSON.parse转换为JS对象。问题是存储的url字符串包含对JSON无效的字符。我得到一个错误: 1_0.html:1 Uncaught SyntaxError: Unexpected token h in JSON at position 0 at JSON.parse (<anonymous>) at trackL

我在一个网站上工作,跟踪用户点击的链接。数据以字符串形式存储在localStorage中。我知道localStorage中的字符串数据可以通过使用JSON.parse转换为JS对象。问题是存储的url字符串包含对JSON无效的字符。我得到一个错误:

1_0.html:1 Uncaught SyntaxError: Unexpected token h in JSON at position 0
    at JSON.parse (<anonymous>)
    at trackLink (tracking_functions.js:318)
    at HTMLAnchorElement.onclick (1_0.html:46)
在通过JSON解析器发送字符串之前,我尝试使用清理字符串,但没有达到目的。我不确定清理字符串是否是一个选项,因为它可能会使url字符串无法作为超链接使用

有没有办法绕过这个问题

encodeURI此函数对特殊字符进行编码,除了:,/?:@&=+$使用encodeURIComponent对这些字符进行编码

encodeURIComponent此函数对特殊字符进行编码。此外,它还编码以下字符:,/?:@&=+$

你必须这样做

var url = "https://a.but/#safe=active&q=sf";
var json = {"link": encodeURIComponent(url)}
localStorage.setItem("urls", JSON.stringify(json));

你拿回来的绳子是什么?@J.Titushttps://history.gmheritagecenter.com/wiki/index.php/History_of_Louis_ChevroletThat是一个URL,不是JSON。您可以直接将其作为字符串使用,而无需使用JSON.parseWell,是的。这几乎就是问题所在。我上面的问题不清楚吗?URL作为字符串存储在localStorage中。我想将它们转换为JS数组,以便在代码中使用它们。转换失败,因为URL字符串包含JSON.parse无法处理的无效字符。您的字符串不包含JSON.parse的无效字符,问题是它不是一个有效的JS对象。尝试使用JSON.stringifyyourTableOfUrlsHere存储数据。然后,您将能够从localStorage中以字符串形式检索该数组,并使用JSON.parse将其转换回数组。