json - 循环遍历 Powershell 中没有键/值对而是值列表的转换后的 json 数据?
问题描述
JSON:
[
{
"Category-1": [
"Value1"
]
},
{
"Category-2": [
"Value1"
]
},
{
"Category-3": [
"Value1",
"Value2"
]
}
]
PowerShell 脚本:
$jsonToParse = (Get-Content -Path $jsonPath) -join "`n" | ConvertFrom-Json
foreach ($entry in $jsonToParse) {
log -Message ($entry) #Log function spits output to file
}
输出:
[10:39:03]@{Category-1=System.Object[]}
[10:39:03]@{Category-2=System.Object[]}
[10:39:03]@{Category-3-Med=System.Object[]}
我该如何解析这个?我有方括号和大括号,我很难找到一个立足点来真正获取数据。
我该怎么做才能获得“类别”名称?我该怎么做才能获得每个类别名称的“值”?我认为,这些并非所有键/值对的事实是给我带来麻烦的原因。
解决方案
我认为你所追求的是这样的:
# use the -Raw switch to get the file content as one single string
$jsonToParse = Get-Content -Path $jsonPath -Raw | ConvertFrom-Json
foreach ($entry in $jsonToParse) {
# format a string for the log file using the object ($entry) Name followed by the Value
# This Value can be an array of more than one items, so join these with a comma
$msg = '{0} = {1}' -f $entry.PSObject.Properties.Name, ($entry.PSObject.Properties.Value -join ', ')
log -Message $msg #Log function spits output to file
}
输出:
[10:39:03]Category-1 = Value1
[10:39:03]Category-2 = Value1
[10:39:03]Category-3 = Value1, Value2
推荐阅读
- python - ValueError:当DF变得太大时,无法将非有限值(NA或inf)转换为整数?
- java - 滚动后的无序 RecycleView 列表
- solr - 在 Solr 中支持多种语言
- prompt - 接收 0 到 120 之间的数字
- linux - 如何使用 GREP 确定文件中的每一行是否与我的模式匹配?
- spring - 为什么在启动期间创建存储库 bean 需要数据源 bean
- elasticsearch - 汇总作业使日期字段的最大聚合为浮动而不是日期
- c# - 响应式 .NET (RX) 通过返回相同的 Observable 嵌套捕获
- python - 使用多处理池时,在 Docker 中运行 python 会卡住
- python - 加快python中的for循环