Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Escape JSON characters #1301

Closed
mirkods opened this issue Jan 23, 2017 · 1 comment
Closed

Escape JSON characters #1301

mirkods opened this issue Jan 23, 2017 · 1 comment

Comments

@mirkods
Copy link

mirkods commented Jan 23, 2017

Hi there,
I'm using handlebars not for what it has borned but for compiling dinamically JSON.

In my case I have something like this:

const handlebars = require('handlebars');

const objToCompile = {
    value: '{{test}}'
}
const objData = {
    test: true
};
const templateString = handlebars.compile(JSON.stringify(objToCompile, {
    noEscape: true
});
const compiledString = templateString(objData);
const compiledResult = JSON.parse(compiledString);    // { test: true }

I don't need the HTML encode so I'm using the noEscape parameter because the compiledResult object is not used to compile any HTML template but only as server side object.

As you can see Handlebars works well in the case above but there are problems when there are characters that break the JSON.parse function as " or \n or \r.

You can see an example of scenario where it doesn't work:

const handlebars = require('handlebars');

const objToCompile = {
    value: '{{test}}'
}
const objData = {
    test: '\n'
};
const templateString = handlebars.compile(JSON.stringify(objToCompile, {
    noEscape: true
});
const compiledString = templateString(objData);
JSON.parse(compiledString);    // Unexpected token \n

Do you have some suggestions about my case?
Mirko

@nknapp
Copy link
Collaborator

nknapp commented Jan 23, 2017

I would not use Handlebars for such a use-case. Instead of generating a template with JSON.stringify it seems much easier and clearer to write a function like:

function transform(objData) {
  return { value: objData.test }
}

The performance should be better as well. You don't have to create a string first and parse it later...

If you still insist on using Handlebars...: There is no officially supported option to change the escaping-behavior of Handlebars (only noEscape), but you can hack it. Of course, hacking means that the hack may be broken in future versions. Here is an example that somehow works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants