storing and retrieving json objects to / from a cookie - javascript

Im attempting to store json objects in a cookie, but im running into a few problems.
I can create my object like this:
product = {
"name" : "prodname",
"quantity" : 4
}
i then save this object in my cookie. As more products are added (its a shopping basket) i add further strings by appending new objects onto the end of the cookie string (so i essentially have lots of small seperate objects) . Im having trouble getting the objects back out of the cookie string though. Both $.parseJSON and eval fail when i attempt to read the objects back from the cookie. Any help would be appreciated.

its not a good practice to save the value that returned from JSON.stringify(cookieStr) to the cookie. it can lead to a bug in some browsers.
before using it you should convert it to base64 (using btoa), and when reading it, converting from base64 (using atob)
val = JSON.stringify(cookieStr)
val = btoa(val)
write_cookie(val)

It should probably be like:
{"products": [
{
"name" : "prodname",
"quantity" : 4
},
{
"name" : "prodname2",
"quantity" : 3
}
]}
The [] signifies an array. When you want add another product, you load it from the cookie, update the array, then save it again. If you wanted, you could skip the outer object and have the cookie just be the array.
EDIT: Say cookieStr is your cookie.
var root = $.parseJSON(cookieStr);
root.products.push(newProduct);
cookieStr = JSON.stringify(root);

Related

What's the fastest way to get all the initial values of a variable? JS

I want to get the initial values (What I first defined it to be) of all the properties for one of my objects.
I want to do this at the "end" of my game.
I could just copy and paste the properties but the object is pretty big and im wondering if this would slow the site down a bit?
Thanks!
Code example:
var MyObject = {
nestedObject1 : {
//...
},
nestedObject2 : {
value1 : "Hi",
value2 : 1
},
objectProperty : 2637
}
How would I get all (Or maybe excluding one of the nested objects) of the properties to their intial value?
I don't quite fully understand how you want to get the initial values, at the end of your running. But probably the easiest way to do this is to just serialize your object to JSON using JSON.stringify.
var original = JSON.stringify(myObject)
Then at the end of your application when you want access to this original object again you can rehydrate it to a new JavaScript object:
original = JSON.parse(original);

In localStorage how do we save similar tuples with index?

In our extension, we are getting values of username( eg: Johnny123), accname (eg: Facebook).
I want to store this for multiple accounts and usernames in the localStorage.
We have written this code :
var i = Number(localStorage.usercounter); // counter for number of users
localStorage.username(i) = username.value; // textbox value
localStorage.accname(i) = accname.value; // textbox value
this code is not executing, what is the right way to store the values?
localStorage.username = username.value;
localStorage.accname = accname.value;
this is executing and allowing us to retrieve values. Please Help.
localStorage stores strings on data-properties...
...your options are:
store a JSON representation of an array which contains user objects
var userdata = [{ name : "Bob", account : "Facebook" },
{ name : "Doug", account : "LinkedIn" }],
userjson = JSON.stringify(userdata);
localStorage.setItem("users", userjson);
console.log(JSON.parse(localStorage.getItem("users")[0].name);
store a JSON/string representation to a suffixed key
localStorage.setItem("user_0_name", "Bob" );
localStorage.setItem("user_0_account", "Tumblr");
localStorage.setItem("user_1_name", "Doug" );
localStorage.setItem("user_1_account", "MySpace");
// ...
As you can see, the first option is the one that makes more sense.
This is how I'd read write it using truStorage (https://github.com/andresgallo/truStorage)
truStorage.setItem('a',{});//This will be the main key, the one localStorage is aware of
truStorage.setItem('a.b',[1,2,3]);//Now we can store variable 'b' inside object a
truStorage.getItem('a'); //returns entire object {a : {b: [1,2,3]}}
truStorage.getItem('a.b') //returns child object {b: [1,2,3]}
You can write directly to child items the same way as you suggested.
truStorage.setItem('a.b.c', 'value of third level nested object c');
In the background this really does the JSON parse/stringify and recursion for you, which will clean up you application massively if you are using lots of localStorage.

localStorage array of objects handling

Array of JSON objects are stored in HTML5 localStorage.
For now delimiter is ;
For accessing and modifying array of objects from localStorage, split(';') and join(';') operations used.
However ,delimiter approach looks unstable.
For instance ; could be met inside objects attribute and split(';') operation will be uncorrect.
It could be used ;; for delimiter,but i'm not certain it will be stable also.
Is there any robust way to handle localStorage presented as array of objects,as far localStorage saved as String?
EDIT
one of stoppers is that array of object couldn't be saved to localStorage as classical: "[{},{}]"
localStorage converts it automatially to String like "{},{}"
my current data within localStorage:
"{"name":"volvo","id":"033"};{"name":"saab","id":"034"}"
assumption
perhaps,i can add [ at the start and ] at the end,but it looks not gracefull
Just convert the objects to JSON strings:
localStorage.setItem("savedData", JSON.stringify(objects));
And vice versa:
objects = JSON.parse(localStorage.getItem("savedData")));
Or you can add multiple objects in the same localStorage value:
localStorage.setItem("savedData", JSON.stringify([object1, object2 /*, etc*/]));
object1 = JSON.parse(localStorage.getItem("savedData"))[0];
object2 = JSON.parse(localStorage.getItem("savedData"))[1];
Here's the DOM storage specification.
You can also access savedData like this:
localStorage.savedData = "Hello world"
var foo = localStorage.savedData;
This can be used for both getting and setting the data, but it is considered less "safe" than getItem('name'); and setItem('name', 'value');
Read variables:
var xyz = JSON.parse( localStorage.getItem( 'element' ) );
Store variables:
localStorage.setItem( 'element' , JSON.stringify(xyz));
where element is the name of the local storage variable and xyz the name of the js variable.

Deserializing JavaScript object instance

I am working on an app that heavily uses JavaScript. I am attempting to include some object-oriented practices. In this attempt, I have created a basic class like such:
function Item() { this.init(); }
Item.prototype = {
init: function () {
this.data = {
id: 0,
name: "",
description: ""
}
},
save: function() {
alert("Saving...");
$.ajax({
url: getUrl(),
type: "POST",
data: JSON.stringify(this.data),
contentType: "application/json"
});
}
}
I am creating Item instances in my app and then saving them to local storage like such:
Item item = new Item();
window.localStorage.setItem("itemKey", JSON.stringify(item));
On another page, or at another time, I am retriving that item from local storage like such:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
Unfortunately, the "save" function does not seem to get reached. In the console window, there is an error that says:
*save_Click
(anonymous function)
onclick*
I have a hunch that the "(anonymous function)" is the console window's way of saying "calling item.save(), but item is an anonymous type, so I am trying to access an anonymous function". My problem is, I'm not sure how to convert "var item" into an Item class instance again. Can someone please show me?
Short answer:
Functions cannot be serialized into JSON.
Explanation:
JSON is a cross-platform serialization scheme based on a subset of JS literal syntax. This being the case, it can only store certain things. Per http://www.json.org/ :
Objects: An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
Arrays: An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).
values: A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.
Functions cannot be serialized into JSON because another non-JS platform would not be able to unserialize and use it. Consider the example in reverse. Say I had a PHP object at my server which contained properties and methods. If I serialized that object with PHP's json_encode() and methods were included in the output, how would my JavaScript ever be able to parse and understand PHP code in the methods, let alone use those methods?
What you are seeing in your resulting JSON is the toString() value of the function on the platform you're using. The JSON serilizer calls toString() on anything being serialized which isn't proper for JSON.
I believe your solution is to stop storing instances in JSON/local storage. Rather, save pertinent data for an instance which you set back to a new instance when you need.
I know this question is answered already, however I stumbled upon this by accident and wanted to share a solution to this problem, if anyone is interested.
instead of doing this:
var item = window.localStorage.getItem("itemKey");
item = JSON.parse(item);
item.save();
do something like this:
// get serialized JSON
var itemData = window.localStorage.getItem("itemKey");
//instantiate new Item object
var item = new Item();
// extend item with data
$.extend(item, JSON.parse(itemData));
// this should now work
item.save();
this will work so long as the function you are wanting to call (ie, save()) is prototypal and not an instance method (often times the case, and is indeed the case in the OP's original question.
the $.extend method is a utility method of jquery, but it is trivial to roll your own.
You cant do that, how can javascript possibly knows that item have a save function ? json doesnt allow functions as datas. just read the json spec , you cant save functions.
what you need to do is to create a serialize and deserialize method in the hash you want to stock. that will specifiy what to export and how you can "wake up" an object after parsing the corresponding json string.
You can only store plain Objects in DOMstorages (cookies, urlparams..., everything that needs [de]serialisation through JSON.stringify/JSON.parse). So what you did when sending the ajax data
ajaxsend(this.data);
also applies to string serialisation. You can only store the data, not the instance attributes (like prototype, constructor etc.). So use
savestring(JSON.stringify(item.data));
which is possible because item.data is such a plain Object. And when restoring it, you will only get that plain data Object back. In your case it's easy to reconstruct a Item instance from plain data, because your Items hold their values (only) in a public available property:
var item = new Item;
item.data = JSON.parse(getjsonstring());
Disclaimer
Not a full time time J.S. Developer, answer may have some minor bugs:
Long Boring Explanation
As mentioned by #JAAulde, your object cannot be serialized into JSON, because has functions, the technique that you are using doesn't allow it.
Many people forget or ignore that the objects that are used in an application, may not be exactly the same as saved / restored from storage.
Short & quick Answer
Since you already encapsulate the data members of your object into a single field,
you may want to try something like this:
// create J.S. object from prototype
Item item = new Item();
// assign values as you app. logic requires
item.data.name = "John Doe";
item.data.description = "Cool developer, office ladies, love him";
// encoded item into a JSON style string, not stored yet
var encodedItem = JSON.stringify(item.data)
// store string as a JSON string
window.localStorage.setItem("itemKey", encodedItem);
// do several stuff
// recover item from storage as JSON encoded string
var encodedItem = window.localStorage.getItem("itemKey");
// transform into J.S. object
item.data = JSON.parse(encodedItem);
// do other stuff
Cheers.

Parse External JSON File with jQuery

I have a 2 MB JSON object that I'm hoping to parse with jQuery. I dumped the whole object into a file named "timeline.js" and I'm hoping to parse through it as a dataset to grab records as needed.
My dataset started as an XML file, but I read that JSON would be more efficient as I'm using jQuery to pull the data and place it in the DOM.
Below is the first record of my object. How would I parse this object to grab the record with a 'profileid' of 1016?
{
timeline:{
record:[
{
profileid:1016,
title:'Adam',
parentprofileid:0,
type:'Person',
minzoomlevel:29,
maxzoomlevel:66,
isapproxstart:1,
isapproxend:1,
startdate:-4181,
enddate:-3251,
shortdescription:'Name means "red" or "man" he is...',
article:'<div><span>The first member of...',
status:22,
scriptures:{
scripture:[
{
profileid:1016,
scripturetext:'Genesis 2:7',
referencetext:'Birth'
},
{
profileid:1016,
scripturetext:'Genesis 5:4',
referencetext:'Death'
}
]
}
},
jQuery parseJSON works fine, however is unnecessary when using jQuery AJAX and set the dataType to JSON (it is already parsed by jQuery after receiving the data).
However, I guess your actual question is how to find the record with the profileid of e.g. 1016. Since all items are in an array, the only way to find it, is to loop the array and check what profileId is set for the current item. For example:
for(var i in items){
if(items[i].profileid == 1016){
//execute whatever you want to do.
}
}
Make use of :jQuery.parseJSON( json ) - Takes a well-formed JSON string and returns the resulting JavaScript object.
Example
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

Categories

Resources