Node.js JSON.stringify() causing " in output. Can't parse with Jquery

Jamis Charles picture Jamis Charles · Jun 22, 2012 · Viewed 75.9k times · Source

I am using Node.js (with Express.js) to pass a JSON data object from the server to the client view.

When I render the JSON object directly to the view I get the JSON object shown on the page as expected (this WORKS):

pageprovider.findAllTag( function(error, pages){
    res.send(pages);
})

And my output looks like this (much bigger, many nested obj)

{"green":{"title":"green","pagesContaining": ""}}

When I try to pass it to my Jade View like this:

pageprovider.findAllTag( function(error, tagsJSONObj){
        //res.send(pages);

    pageprovider.findAll( function(error, pages){
        res.render('search_tags.jade', { locals: {
            title: 'Search by Tags',
            'pages': pages,
            tagsJSON: JSON.stringify(tagsJSONObj) //pass the tags data as a JSON obj
            }
        });
    }) //pageprovider.findAll
}) //pageprovider.findAllTag

The problem
When I pass 'tagsJSON' to the view, the output includes the html entities:

var obj = jQuery.parseJSON( "{"name": 'value'}");

JQuery throws an error because it doesn't like '"'. How can I get Node to give me the proper quote, or get jQuery to accept this format?

Any thoughts?

Answer

Juan Mendes picture Juan Mendes · Jun 22, 2012

It's because when you call

    res.render('search_tags.jade', { locals: {
        title: 'Search by Tags',
        'pages': pages,
        tagsJSON: JSON.stringify(tagsJSONObj) //pass the tags data as a JSON obj
        }
    });

search_tags.jade is meant to output HTML, so it encodes your quotes. You should use a renderer that doesn't HTML escape, or at least change your view so that your params aren't HTML encoded

If you don't want something in the output escaped, use !{tagsJSON} within the view. However, when outputting JSON, there's no need for a view. you can just take your object, call JSON.stringify. I don't use JADE so I'm not sure if there is a way to create view that can just call JSON.stringify(), but that's what I've done in JSP, velocity, ASP, PHP and Code Igniter (not using JSON.stringify, instead it uses a JSON tool for the given language)