在我的 ASP.NET MVC Web 项目中,我有许多 JSON 文件。File1.json
{
"manage_employees_section_title":
{
"value": "Manage employees",
"description": "The mange employees section title"
}
}
File2.json
{
"manage_operations_section_title":
{
"value": "Manage operations
"description": "The mange operations section title"
}
}
作为构建过程的一部分,我需要获取我所有的
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>
这就是我得到的......
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"
}
}
虽然达到了拼接的目的,但我真正想要的是合并所有
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"
}
}
作为使用 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>
结果,您将拥有以下文件:
{
"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"
}
}
这种方法不够灵活,例如它需要将尾括号放在源文件的第一个和最后一个位置。无论如何,仅演示如何使用 MBSuild 就足够了。
关于json - 使用 MSBuild 将多个 JSON 文件合并为一个 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28993751/