admin管理员组文章数量:1221467
I have a function to return a json string in this format:
{"TownA":{"female":512,"male":468},"TownB":{"female":748,"male":845}}
I'd like to append the data to a CSV:
town, value, gender
TownA, 512, female
TownA, 468, male
TownB, 748, female
TownB, 845, male
I think I need to first convert it to a custom object, like this:
$Line= [pscustomobject] @{
'Town' = [STRING]""
'Value' = [FLOAT]""
'sex' = [STRING]""
}
But I'm not sure. How can append this data to my csv?
I have a function to return a json string in this format:
{"TownA":{"female":512,"male":468},"TownB":{"female":748,"male":845}}
I'd like to append the data to a CSV:
town, value, gender
TownA, 512, female
TownA, 468, male
TownB, 748, female
TownB, 845, male
I think I need to first convert it to a custom object, like this:
$Line= [pscustomobject] @{
'Town' = [STRING]""
'Value' = [FLOAT]""
'sex' = [STRING]""
}
But I'm not sure. How can append this data to my csv?
Share Improve this question edited Feb 8 at 2:25 mklement0 438k68 gold badges701 silver badges911 bronze badges asked Feb 7 at 13:51 TheRob87TheRob87 1346 bronze badges2 Answers
Reset to default 2What you got from your function is a Json string, you can use ConvertFrom-Json
to parse it into object, from there you will have to enumerate the properties and nested properties to get the desired output:
$json = ConvertFrom-Json '{"TownA":{"female":512,"male":468},"TownB":{"female":748,"male":845}}'
$json.PSObject.Properties | ForEach-Object {
foreach ($property in $_.Value.PSObject.Properties) {
[pscustomobject]@{
Town = $_.Name
Value = $property.Value
Gender = $property.Name
}
}
} # Can pipe to Export-Csv from here
Your string is a JSON.
There are multiple way to manipulate it.
If you are using Powershell Core/7.x you can use this
# Replace with however you are getting the JSON.
$JsonString = '{"TownA":{"female":512,"male":468},"TownB":{"female":748,"male":845}}'
$JsonHashtable = $JsonString | ConvertFrom-Json -AsHashtable
$ConvertedArray = foreach ($Key in $JsonHashtable.Keys) {
foreach ($Gender in $JsonHashtable.$Key.Keys) {
# casting to [Ordered] is actually superfluous unless you REALLY need
# the columns being in a specific order.
[ordered]@{
'town' = $Key
'value' = $JsonHashtable.$key.$Gender
'gender' = $Gender
}
}
}
$ConvertedArray | Export-Csv -Path $CsvPath
本文标签: jsonPowershell formatted String(2Dim Array) to CSVStack Overflow
版权声明:本文标题:json - Powershell: formatted String(2Dim Array) to CSV - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739319113a2157950.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论