1

Having issues with Jade and the way the data is passed to it when it is rendered.

I am trying to save the data which is in [{key1: "val1", key2: "val2"}, ...}]; format but having issues as it shows up as the result below.

Result

key: xyz value:[{"artist":"Lady Gaga",...

This is the code I am working with on the server-side Node.js which is passing it fine ...

res.render('musics', {
    title: 'site',
    result: JSON.stringify(result)
});

This is the code I am having issues with because of the way I have to call result in jade...

script
    function local (arr) {
        var i;
        i = "#{result}";
        localStorage.setItem('xyz', i);
    }
    console.log('stored');
    local();

The quotes around result are messing it up but without them I get an error for unexpected identifier...

Any suggestions or if it might be better to go an ajax route through Backbone(which is what I am using with the client-side) I am willing to, just to put some pointers out - the data is being scraped and through selections of a form post - so the data comes back after the post and is a on time transfer, so if I did an ajax call it would have to include the post and the get, otherwise i am not sure of how to receive it... maybe res.json(result) on the server side, but then the page needs to render somehow... Open to suggestions. Thanks! Ultimately I want it to go into localStorage without the " around everything.

Lion789
  • 4,292
  • 12
  • 56
  • 93

2 Answers2

2

your jade snippet should look like this then:

script!= "(function() {localStorage.setItem('xyz',JSON.stringify(" +result + ");})();"

by using != you tell jade to not escape the following content, and on the clientside you have to stringify again before puting your data to local storage.

greelgorke
  • 366
  • 1
  • 5
0

As an improvement to @greelgork's answer:

This is for JSON array

script!= "(function() {var items = []; items = JSON.parse(localStorage.getItem('Stored_items')); console.log(JSON.stringify(items)); items.push(" + JSON.stringify(product) + "); localStorage.setItem('Stored_items', JSON.stringify(items)); })();"

Anyways, pushing an item into localStorage needs to be stringified before inserted into localStorage hence, @greelgorke's answer should be modified so:

single item

script!= "(function() {localStorage.setItem('xyz',JSON.stringify(result)); })();"

So the JSON.stringify is outside the string just like all the other javascript code is,
This is what I use in my project and it worx

Credit Push JSON Objects to array in localStorage

Community
  • 1
  • 1
Jadeye
  • 2,855
  • 3
  • 44
  • 58