0

I am working on a website that tracks which links the user has clicked. The data is stored as a string in localStorage. I know that string data in localStorage can be converted to JS objects by using JSON.parse. The problem is that the stored url strings contain characters that aren't valid for JSON. I am getting the error:

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)

I tried cleaning the string before sending it through the JSON parser using this suggestion but that didn't do the trick. And I am not sure if cleaning the string is even an option because it might make the url string unusable as a hyperlink.

Is there a way to get around this?

Community
  • 1
  • 1
  • 1
    What is the string you get back? – J. Titus May 18 '17 at 17:39
  • @J.Titus `https://history.gmheritagecenter.com/wiki/index.php/History_of_Louis_Chevrolet` – Guybrush Threepwood May 18 '17 at 17:40
  • 1
    That's a URL, not JSON. You can use it directly as a string without using `JSON.parse` – J. Titus May 18 '17 at 17:41
  • Well, yes. That's pretty much the issue. Is that not clear from my question above? The URLs are stored as strings in `localStorage`. I would like to convert them to JS arrays so I can work with them in my code. The conversion fails because the URL strings contain invalid characters that `JSON.parse` can't handle. – Guybrush Threepwood May 18 '17 at 17:44
  • 1
    Your string doesn't contain invalid characters for `JSON.parse`, the problem is that it's not a valid JS object to begin with. Try storing data using `JSON.stringify(yourTableOfUrlsHere)`. Then you'll be able to retrieve that array as a string from `localStorage` and use `JSON.parse` to turn it back into an array. – J. Titus May 18 '17 at 17:48
  • Thanks, that was part of the problem. As you guessed, when populating `localStorage`, I didn't do it as a stringified `JSON` object so when retrieving the value, it couldn't be parsed. However, now that that's fixed I am running into another problem. I'll create a separate question for that. – Guybrush Threepwood May 18 '17 at 20:38

1 Answers1

1

encodeURI() This function encodes special characters, except: , / ? : @ & = + $ # (Use encodeURIComponent() to encode these characters).


encodeURIComponent() This function encodes special characters. In addition, it encodes the following characters: , / ? : @ & = + $ #

You have to do it this way

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