使用Shell脚本将.txt转换为json

时间:2018-03-02 10:47:27

标签: json shell jq

我有一个文本文件data.txt

Framework1,Version1
Framework2,Version2
Framework3,Version3

我需要将其转换为data.json,如下所示:

[
{"FrameworkName":"Framework1", "VersionName":"Version1"},
{"FrameworkName":"Framework3", "VersionName":"Version2"},
{"FrameworkName":"Framework3", "VersionName":"Version3"}
]

我尝试使用awk,但它对我没什么帮助。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:3)

jq -Rs '[ split("\n")[] | select(length > 0) | split(",") | {FrameworkName: .[0], VersionName: .[1]} ]' data.txt 解决方案:

[
  {
    "FrameworkName": "Framework1",
    "VersionName": "Version1"
  },
  {
    "FrameworkName": "Framework2",
    "VersionName": "Version2"
  },
  {
    "FrameworkName": "Framework3",
    "VersionName": "Version3"
  }
]

输出:

public class LoginViewComponent : ViewComponent
{
    private readonly UserManager<ApplicationUser> _userManager;

    public LoginViewComponent(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        var user = await _userManager.GetUserAsync(HttpContext.User).ConfigureAwait(false);
        return View(user);
    }
}

https://stedolan.github.io/jq/manual/v1.5/