Node.js JSON.stringify()导致& quot;在输出。不能用Jquery解析 [英] Node.js JSON.stringify() causing " in output. Can't parse with Jquery

查看:910
本文介绍了Node.js JSON.stringify()导致& quot;在输出。不能用Jquery解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Node.js(使用Express.js)将JSON数据对象从服务器传递到客户端视图。

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

当我呈现JSON对象直接到视图,我按预期得到页面上显示的JSON对象(这个WORKS):

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);
})

我的输出看起来像这样(更大,很多嵌套obj)

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






问题

当我将'tagsJSON'传递给视图时,输出包括html实体:


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

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

JQuery抛出错误,因为它不喜欢。如何让Node给我正确的引用,或者让jQuery接受这种格式?

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?

任何想法?

推荐答案

这是因为当你调用

    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 旨在输出HTML ,所以它编码您的报价。您应该使用不会HTML转义的渲染器,或至少更改您的视图,以使您的参数不是HTML编码。

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

如果您不想要输出转义,在视图中使用!{tagsJSON} 。但是,当输出JSON时,不需要查看。你可以拿你的对象,调用 JSON.stringify 。我不使用JADE,所以我不知道是否有办法创建可以调用 JSON.stringify()的视图,但这就是我所做的在JSP,速度,ASP,PHP和代码Igniter(不使用 JSON.stringify ,而是使用给定语言的JSON工具)

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)

这篇关于Node.js JSON.stringify()导致& quot;在输出。不能用Jquery解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆