3

I have the following express route:

var data = [
    {
        id: 1,
        title: 'aide-memoire'
    },
    {
        id:2,
        title: 'apres moi'
    }
];

app.get('/', function (req, res) {
    res.render('photo/list', {
        data: data
    });
});

In my JADE template I'm getting that data like the following:

!!!5
html
    head
    body
        script
            var data = !{JSON.stringify(calculates)};

But I get that data array on a client like this:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <script type="text/javascript">
        var data = [
            { "id":1, "title": 'aide-memoire'},
            { "id":2, "title": 'apres moi'}
        ];
        </script>
    </body>
</html>

But I need to encode non-ASCII characters as \uXXXX sequences like the following:

[
    {"id":1, "title": "aide-m%E9moire"},
    {"id":2, "title": "apr%E8s%20moi"}  
]

How can I do that in express/jade?

3
  • Have you looked at this nodejs.org/api/buffer.html?
    – saada
    Commented Mar 24, 2013 at 8:57
  • How should I use that for my case?
    – Erik
    Commented Mar 24, 2013 at 9:10
  • It looks like the encoding you are looking for is unicode hex escape characters... I'm not sure how they work... try to google these keywords... good luck
    – saada
    Commented Mar 24, 2013 at 9:12

1 Answer 1

6
JSON.stringify(["ä", "ä"]).replace(/[\u0080-\uFFFF]/g, function(m) {
    return "\\u" + ("0000" + m.charCodeAt(0).toString(16)).slice(-4);
});
//["\u00e4","\u00e4"]

JSON.stringify([{title: "ä"}, {title: "ä"}]).replace(/[\u0080-\uFFFF]/g, function(m) {
    return "\\u" + ("0000" + m.charCodeAt(0).toString(16)).slice(-4);
});
//[{"title":"\u00e4"},{"title":"\u00e4"}]

Although this is completely useless and it eats CPU for nothing to provide larger responses :/ Remember that each CPU cycle used in node.js is a CPU cycle where the entire server is down unless you cluster.

3
  • What's about array of objects? [{title: "ä"}, {title: ""ä""}]
    – Erik
    Commented Mar 24, 2013 at 17:54
  • Shouldn't make a difference since the whole thing is being stringified Commented Mar 24, 2013 at 17:57
  • This is great for converting properties strings, like native2ascii does (without the JSON stringifying, of course). propetiesString.replace(...) --- thanks a lot.
    – noderman
    Commented Feb 17, 2016 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.