koo*_*e98 5 msbuild json build-process csproj visual-studio
在我的 ASP.NET MVC Web 项目中,我有许多 JSON 文件。
File1.json
{
"manage_employees_section_title":
{
"value": "Manage employees",
"description": "The mange employees section title"
}
}
Run Code Online (Sandbox Code Playgroud)
File2.json
{
"manage_operations_section_title":
{
"value": "Manage operations
"description": "The mange operations section title"
}
}
Run Code Online (Sandbox Code Playgroud)
作为构建过程的一部分,我需要将所有内容JSONs合并到一个文件中。
我已经这样使用MSBuild了。
<Target Name="ConcatenateJsFiles">
<ItemGroup>
<ConcatFiles Include="Application\**\resource-content*.json"/>
</ItemGroup>
<ReadLinesFromFile File="%(ConcatFiles.Identity)">
<Output TaskParameter="Lines" ItemName="ConcatLines"/>
</ReadLinesFromFile>
<WriteLinesToFile File="Infrastructure\Content\Store\ContentStore.json" Lines="@(ConcatLines)" Overwrite="true" />
</Target>
Run Code Online (Sandbox Code Playgroud)
这就是我得到的......
Concat.json
//What I got
{
"manage_employees_section_title":
{
"value": "Manage employees",
"description": "The mange employees section title"
}
}
{
"manage_operations_section_title":
{
"value": "Manage operations
"description": "The mange operations section title"
}
}
Run Code Online (Sandbox Code Playgroud)
尽管我已经实现了串联的目标,但我真正想要的是将所有JSON文件合并到一个JSON对象中。
//What I really want
{
"manage_employees_section_title":
{
"value": "Manage employees",
"description": "The mange employees section title"
},
"manage_operations_section_title":
{
"value": "Manage operations
"description": "The mange operations section title"
}
}
Run Code Online (Sandbox Code Playgroud)
作为使用 Visual Studio 构建过程的一部分,我如何才能实现这一目标。
非常感谢你们。
仅使用 MSBuild 功能获取结果是一项有趣的任务...说实话,为此目标创建额外的 C# 应用程序是更好的方法。但我也可以使用 MSBuild 做到这一点:
<Project ToolsVersion="12.0" DefaultTargets="ConcatenateJsFiles" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" >
<Target Name="ConcatenateJsFiles">
<ItemGroup>
<ConcatFiles Include="Application\**\resource-content*.json"/>
</ItemGroup>
<ItemGroup>
<!-- Read file content (with spaces preserving), remove trailing { and } -->
<ContentLines Include="$([System.IO.File]::ReadAllText('%(ConcatFiles.Identity)').Remove($([MSBuild]::Subtract($([System.IO.File]::ReadAllText('%(ConcatFiles.Identity)').Length), 1)), 1).Remove(0, 1))"/>
<!-- Create resulting file with trailing { and } -->
<FileContent Include="{"/>
<FileContent Include="@(ContentLines, ',%0a')"/>
<FileContent Include="}"/>
</ItemGroup>
<WriteLinesToFile File="ContentStore.json" Lines="@(FileContent)" Overwrite="true" />
</Target>
</Project>
Run Code Online (Sandbox Code Playgroud)
结果你将得到以下文件:
{
"manage_employees_section_title":
{
"value": "Manage employees",
"description": "The mange employees section title"
},
"manage_operations_section_title":
{
"value": "Manage operations",
"description": "The mange operations section title"
}
}
Run Code Online (Sandbox Code Playgroud)
这种方法不够灵活,例如它需要尾大括号位于源文件的第一个和最后一个位置。无论如何,仅演示如何使用 MBSuild 就足够了。
| 归档时间: |
|
| 查看次数: |
3376 次 |
| 最近记录: |