Json到CSV选择第二级列

时间:2016-12-22 06:58:22

标签: powershell

我有一个以下格式的json,其中一些列位于第二级。我希望第二级的列位于CSV的第一级

{
  "ApiKey": "123",
  "BasicDetails": {
    "ClientID": "1234",
    "CompanyName": "C1",
    "ContactName": "",
    "EmailAddress": "",
    "Country": "United Kingdom",
    "TimeZone": "(GMT+00:00)"
  }}

必需的输出是:

APIKey, ClientID, CompanyName, ContactName, EmailAddress,Country,Timezone
123,1234,C1,,,United Kingdom,(GMT+00:00)

我试过了:

(GET-Content F:/my.json -RAW | ConvertFrom-Json)|Select Columns|Export-CSV F:/my.csv

修改 实际的Json: {

    "ApiKey": "123",
      "BasicDetails": {
        "ClientID": "1234",
        "CompanyName": "C1",
        "ContactName": "",
        "EmailAddress": "",
        "Country": "United Kingdom",
        "TimeZone": "(GMT+00:00)"
      }
    "BillingDetails": {
    "CurrentTier": "0 - 500",
    "CurrentMonthlyRate": 9.0000,
    "MarkupPercentage": 0,
    "MonthlyScheme": "Basic",
    "Currency": "USD",
    "ClientPays": false
  }}

我需要在一个级别提供Belling Detail列,Basic Details列和API密钥

2 个答案:

答案 0 :(得分:1)

这适用于深度为2(您请求的)的所有JSON文件:

$tempObject = @{}

(GET-Content F:/my.json -RAW | convertfrom-json).PsObject.Properties | ForEach-Object {
    if ($_.TypeNameOfValue -eq 'System.Management.Automation.PSCustomObject')
    {
        $_.Value.PsObject.Properties | ForEach-Object {
            $tempObject  += @{$_.Name = $_.Value}
        }        
    }
    else
    {
        $tempObject  += @{$_.Name = $_.Value}
    }
} 
[PsCustomObject]$tempObject | Export-CSV F:/my.csv

答案 1 :(得分:0)

棘手的问题。如果您正在为特定案例或更一般的方法寻找解决方案,那么非常依赖。

首先,请参阅Martin Brandl的回答。

另外,还有ConvertTo-FlatObject

https://gallery.technet.microsoft.com/ConvertTo-FlatObject-396a6e0a