3

I have a array fields which contain a list of strings:

var fields = ['foo', 'bar', 'zed'];

I pass it to pug from express like this:

app.get('/some_route', function(req, res) {

    res.render('some_view', { fields: fields });

});

Now I want to use that array inside jquery script, I already try:

<script>
    $( document ).ready(function() {
        var fields = #{fields};
        // return: var fields = foo,bar,zed;
    });
</script>

and:

<script>
    $( document ).ready(function() {
        var fields = JSON.parse(#{fields});
        // return: var fields = JSON.parse(foo,bar,zed);
    });
</script>

thanks

1 Answer 1

5

JSON-encode it an put it in an attribute somewhere, like on the <script> itself:

script(id='field-source', data-fields=JSON.stringify(fields)).
    $(document).ready(function () {
        var fields = JSON.parse($('#field-source').data('fields'));
    });

It’s possible to put it directly into the script with some careful escaping¹ (JSON-encoding is not enough!), but not worth the effort when attributes already work so reliably.

¹ You start by JSON-encoding, then make it safe for the JavaScript context by replacing U+2028 and U+2029 with \u202[89], then make it safe for the HTML context by replacing < with \x3c. Replacing only </ is not enough, as <!-- can also mess with parsing in certain contrivable ways.

Sign up to request clarification or add additional context in comments.

3 Comments

based on your answer this should work too: ` var fields = JSON.parse(#{JSON.stringify(customerFields)}) ` ?
I get this work by only add : ` var fields = !{JSON.stringify(customerFields)} `
@younel: That’s exactly what I said not to do. It’s an HTML injection (“XSS”) vulnerability.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.