0

I have a Javascript object (or array of objects?) of the form:

   [{"id":"1","col":"0.35","type":"1"},{"id":"2","col":"0.30","type":"1"},{"id":"11","col":"0.20","type":"0"}]

I want to turn this into a URL and then be able to parse this URL back into the same form when the page loads. I would also like to add a title element to the front of the URL which would be stripped off before re-creating the object. So the URL for the above might look like: (i don't need the keys as the urls could be long)

http://example.com/myURL.html?Page_Title&1,0.35,1&2,0.30,1&11,0.20,0

Then when the page loads I'd remove 'Page_Title' and re-create the object, adding back in the id: , col: and type: keys).

The URL could potentially hold dozens of {id,col,type} groups.

I'm working with this function but I can't seem to get it working. I'm sure it's something simple that I've misunderstood or overlooked.

  function ArrayToURL(array,title) {
    var pairs = [];
     for (var key in array)
     if (array.hasOwnProperty(key))
     pairs.push(encodeURIComponent(array[key])); 
     my_title=(encodeURIComponent(title)); 
     return ("http://example.com/myURL.html?")+my_title+'&'+pairs.join('&'); 
    }
2
  • 1
    Why json data in URL ? Commented Jun 10, 2016 at 0:57
  • I'm storing settings in localStorage. The URL is being parsed from a stored localStorage string and will then eventually go back there. Does that make sense? Commented Jun 10, 2016 at 0:59

1 Answer 1

1
function ArrayToURL(array,title) {
var pairs = [];
for (var key in array){

var obj = array[key];
var temp='';

for(var key in obj){
    temp+=obj[key]+",";
}

pairs.push(temp); 

}

 my_title=(encodeURIComponent(title)); 

 return ("http://example.com/myURL.html?")+my_title+'&'+pairs.join('&'); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

This looks much better than mine. Could you give me an idea of how to convert this URL back into the object?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.