Today, I spent almost three hours to test and implement a mechanism to save a complex JSON object and get it to render in a HTML output,, for this reason I would like to explain what was the
best easiest way that I found for saving my object.
Creating our complex JSON object
I have decided to use PHP to create our testing object (because most of developers have knowledge in this programming language).
// An array to simulate a complex JSON object
$userSettings = array(
"personal_information" => array(
"name" => "Alex",
"last_name" => "Arriaga"
"extra_information" => array(
"twitter" => "alex_arriaga_m",
"facebook" => "alex.arriaga.m",
"website" => "http://www.alex-arriaga.com/",
// Creating the JSON object
$jsonObject = json_encode($userSettings);
Saving and getting our complex JSON object
//A cookie by the name 'userSettings' now exists with a serialized copy of $userSettings
$.cookies.set( 'userSettings', <?php echo $jsonObject; ?> );
//A variable named 'userSettings' now holds the unserialized object, it should be identical to the PHP variable 'userSettings'
var userSettings = $.cookies.get( 'userSettings' );
// Do something with the values read from cookie
To see the saved object please use Firebug (in cookie tab). See next images like a demo of this.
Figure 1. Saving JSON object
Figure 2. Getting JSON object and verifying in Firebug console
It is possible to configure several parameters, but I think is better for you read them in the official github page of this plugin: https://code.google.com/p/cookies/
You can download this example code for testing more parameters or personalize according to your project. Download here.
That’s it. Be happy with your code!