如何在 PowerShell 中将键添加到值并转换为 json?
How to add keys to values and convert to json in PowerShell?
我有这样的字符串:
$string = "PackageName1,1,C:\Path
PackageName2,12,C:\Path2
PackageName3,3,C:\Path3"
(是一个多行的文件,当我得到内容时我有上面的字符串)
我想将此字符串转换为 Json:
[
{
Pacakge: "PackageName1",
Branch: = "1",
LocalPath = "C:\Path"
}
{
Pacakge: "PackageName2",
Branch: = "2",
LocalPath = "C:\Path2"
}
]
我可以用这段代码获取值:
$spiltted = $string.Split(' ')
ForEach ($s in $splitted)
{
$values = $s.Split(',')
}
如何将 Json 键添加到每个值并将其转换为 Json 对象?
谢谢。
因为你的字符串看起来像一个没有 headers 的 csv:
$string | ConvertFrom-Csv -Header Package,Branch,LocalPath|ConvertTo-Json
示例输出
[
{
"Package": "PackageName1",
"Branch": "1",
"LocalPath": "C:\Path"
},
{
"Package": "PackageName2",
"Branch": "12",
"LocalPath": "C:\Path2"
},
{
"Package": "PackageName3",
"Branch": "3",
"LocalPath": "C:\Path3"
}
]
我有这样的字符串:
$string = "PackageName1,1,C:\Path
PackageName2,12,C:\Path2
PackageName3,3,C:\Path3"
(是一个多行的文件,当我得到内容时我有上面的字符串)
我想将此字符串转换为 Json:
[
{
Pacakge: "PackageName1",
Branch: = "1",
LocalPath = "C:\Path"
}
{
Pacakge: "PackageName2",
Branch: = "2",
LocalPath = "C:\Path2"
}
]
我可以用这段代码获取值:
$spiltted = $string.Split(' ')
ForEach ($s in $splitted)
{
$values = $s.Split(',')
}
如何将 Json 键添加到每个值并将其转换为 Json 对象?
谢谢。
因为你的字符串看起来像一个没有 headers 的 csv:
$string | ConvertFrom-Csv -Header Package,Branch,LocalPath|ConvertTo-Json
示例输出
[
{
"Package": "PackageName1",
"Branch": "1",
"LocalPath": "C:\Path"
},
{
"Package": "PackageName2",
"Branch": "12",
"LocalPath": "C:\Path2"
},
{
"Package": "PackageName3",
"Branch": "3",
"LocalPath": "C:\Path3"
}
]