使用grunt-contrib-concat组合JSON文件
Combine JSON files with grunt-contrib-concat
我正在寻找在文件夹中组合json文件的最佳方法。
对于HTML, CSS和JavaScript,这是非常容易的,因为你不需要一个分隔符或只有一个单独的;
。然而,对于JSON,我们需要更多的东西来使它成为一个有效的JSON对象。
一种方法是将文件与,
连接起来,并将所有内容包装在数组中。我想知道是否有更好/更简单的方法来做这件事。
Gruntfile.js
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
json: {
src: ['src/**/*.json'],
dest: 'dist/combined.json',
options: {
...
}
}
}
});
src/file1.json
{
"number": 1
}
src/file2.json
{
"number": 2
}
dist/combined.json
这将是期望的结果:
{
"numbers": [
{
"number": 1
},
{
"number": 2
}
]
}
您应该能够使用横幅和页脚选项。
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
json: {
src: ['src/**/*.json'],
dest: 'dist/combined.json',
options: {
// Added to the top of the file
banner: '{"numbers": [',
// Will be added at the end of the file
footer: "]}",
separator: ','
}
}
}
});
你应该使用一个专门的和面向JSON的插件来处理。不只是一个任意的字符串concat。
查看https://github.com/rse/grunt-merge-json或https://github.com/shinnn/grunt-merge-data
您可以使用grunt-merge-json。
使用例子:
假设我们有以下类型的源JSON文件:
src/foo/foo-en.json:
{
"foo": {
"title": "The Foo",
"name": "A wonderful component"
}
}
src/bar/bar-en.json:
{
"bar": {
"title": "The Bar",
"name": "An even more wonderful component"
}
}
假设我们要生成以下目标JSON文件:
{
"foo": {
"title": "The Foo",
"name": "A wonderful component"
},
"bar": {
"title": "The Bar",
"name": "An even more wonderful component"
}
}
单个文件每个目标变量
grunt.initConfig({
"merge-json": {
"en": {
src: [ "src/**/*-en.json" ],
dest: "www/en.json"
},
"de": {
src: [ "src/**/*-de.json" ],
dest: "www/de.json"
}`enter code here`
}
});
每个目标变量有多个文件
grunt.initConfig({
"merge-json": {
"i18n": {
files: {
"www/en.json": [ "src/**/*-en.json" ],
"www/de.json": [ "src/**/*-de.json" ]
}
}
}
});
相关文章:
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 在使用Polymer'加载所有json文件后执行方法;s的核心ajax
- 不显示带有本地json文件数据的谷歌地图脚本
- 可以't使用Appcelerator将JSON文件解析为JavaScript中的TableView
- 加载两个具有相同父密钥名称的json文件
- 使用JSON文件中的变量(字符串)填充文本区域
- 动态显示JSON文件内容
- 将JSON转换为放入Sdcard中的CSV文件
- 正在尝试将JSON文件放入JS数组
- 如何检查Json文件更新,如果更新了,则用更新的数据刷新我的页面
- 单击按钮更改加载到表中的JSON文件
- 创建一个包含两个文件 json 的 Angularjs 过滤器
- Multer上传文件+JSON对象
- 使用node.js读取和写入文件(JSON)
- 如何在angularjs中设置变量's值来上传文件json数据
- 向现有文件. Json写入Json,没有“语法错误”
- 如何保存更新json(文件json)与jquery或javascript
- AngularJS:当使用$http请求一个文件(json content)时发生SyntaxError
- 如何简化此代码?将文件json转换为数组json
- 如何从外部文件JSON创建JAVASCRIPT数组