在JSON.stringify中转义单引号 [英] Escape single quotes in JSON.stringify

查看:1421
本文介绍了在JSON.stringify中转义单引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,我不需要,但我认为我确实需要.

I know, I don't need it, but I think I actually do.

我想在handlebarsjs 之前渲染有效的JS代码,甚至将其渲染. JS缩小工具只是缩小有效的JS文件,而即时缩小会增加处理时间.这是JS车把代码.

I want to have a valid JS code rendered by handlebarsjs before it is even rendered. The JS minification tools just minify valid JS files and minifying on the fly increases processing time. This is the JS handlebars code.

var stringsObj = JSON.parse('{{{ json stringsDataObj }}}');

如您所见,单引号括起来-使该行代码成为 valid JS代码. handlebars助手是:

As you see, the single quotes up-there make that line of code a valid JS code. The handlebars helper is:

function json(context) {
    return JSON.stringify(context);
}

这是什么问题?好吧,stringObj中的某些项目恰好有单引号

And what's the problem? Well, some of the items in stringObj happen to have single quotes

stringsDataObj = {
  "str1": "I'm here",
  "str2": "You're there"
}

当它渲染时

var stringsObj = JSON.parse('"str1": "I'm here", "str2": "You're there"');

出现JS错误

是否可以在JSON.stringify中转义单引号? 我尝试使用替代功能,但没有成功.

Is there a way to escape also single quotes in JSON.stringify? I tried with a replacer function, but without success.

推荐答案

此处实际呈现的 应该是:

What should actually be rendered here is:

var stringsObj = JSON.parse('{"str1": "I'm here", "str2": "You're there"}');

JSON是有效的Javascript代码,在语法上是Javascript的子集.这意味着JSON.stringify输出的是有效的Javascript文字.实际上,您不需要经历生成JSON并确保它是有效的 Javascript字符串文字的麻烦.然后使用JSON.parse进行解析.您只要这样做:

JSON is valid Javascript code, it's syntactically a subset of Javascript. Which means JSON.stringify is outputting a valid Javascript literal. You don't actually need to go through the complications of generating JSON and then ensuring it's a valid Javascript string literal which you then parse with JSON.parse. You just do:

var stringsObj = {{{ json stringsDataObj }}};

哪个渲染:

var stringsObj = {"str1": "I'm here", "str2": "You're there"};

这是有效的Javascript对象文字.

Which is a valid Javascript object literal.

这篇关于在JSON.stringify中转义单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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