[英]Read file using JSON
I am making an application using node.js with express.js, and instead of using JADE, I am using EJS (Embedded Javascript). 我正在使用node.js和express.js制作应用程序,而不是使用JADE,而是使用EJS(嵌入式Javascript)。 When I send(response) information to be plugged into my template I usually send as JSON file, but sometimes I want the JSON file have big chunk of HTML code. 当我发送(响应)信息以插入我的模板时,我通常以JSON文件的形式发送,但是有时我希望JSON文件具有很大的HTML代码块。 This is what I have: 这就是我所拥有的:
This is what I need: 这就是我需要的:
I need: 我需要:
{
"title": "Test blog post",
"paragraph": fs.readFileSync(blogPost.html)
}
replace the fs.readFileSync() with whatever I would use in JSON to read a file. 将fs.readFileSync()替换为我将用于JSON读取文件的任何内容。
As per this answer , JSON is a data description language, not a programming language. 按照这个答案 ,JSON是一种数据描述语言,而不是编程语言。 Therefore, it is not possible to execute a function within JSON. 因此,无法在JSON中执行功能。 I would execute the fs.readFileSync
when the request is made to your server and include that data as a variable within the JSON model response itself. 当对您的服务器发出请求时,我将执行fs.readFileSync
并将该数据作为变量包含在JSON模型响应本身中。 See this answer for more on that, although they're discussing it within the context of PHP, similar principles should apply. 有关此内容的更多信息,请参见此答案 ,尽管他们是在PHP上下文中进行讨论的,但应遵循类似的原则。 This blog post should help as well. 这篇博客文章也应该有所帮助。 Note the intricacy involved in making sure the proper characters are escaped and everything is formatted correctly. 请注意确保转义正确的字符并正确格式化所有内容所涉及的复杂性。
EDIT 编辑
Here(validator.js) is a nice module to help with the html escaping/validation before you send it off with the rest of the JSON. Here(validator.js)是一个很好的模块,可在您将其与其他JSON一起发送之前帮助html转义/验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.