如何在golang中将输出exec命令转换为json

时间:2019-07-10 07:39:53

标签: json go exec

我在golang上使用了exec.Command(command)并将其转换为字符串。 当我在windowOS上运行Command systeminfo时,它返回字符串类型key:value。如何将其转换为json?

enter image description here

代码:

// Version Function:
func Version() (version string) {
    os := OS()
    if os == "macOS X" {
        result := RunCommand("sw_vers")
        resultRune := []rune(result)
        version = string(resultRune[38:43]) // tested
    }
    if os == "Windows" {
        result := RunCommand("systeminfo")
        resultRune := []rune(result)
        version = string(resultRune[:]) // not tested
    }
    if os == "Linux" {
        result := RunCommand("lsb_release -a")
        resultRune := []rune(result)
        version = string(resultRune[:]) // not tested
    }
    return version
}
// RunCommand Function:
func RunCommand(command string) string {
    cmd := exec.Command(command)
    var stdout, stderr bytes.Buffer
    cmd.Stdout = &stdout
    cmd.Stderr = &stderr
    err := cmd.Run()
    if err != nil {
        log.Fatalf("Command "+command+" failed with %s\n", err)
    }
    outStr := string(stdout.Bytes())
    return outStr
}

0 个答案:

没有答案