首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >需要在powershell中将嵌套的Json响应转换为csv

需要在powershell中将嵌套的Json响应转换为csv
EN

Stack Overflow用户
提问于 2016-07-06 05:35:36
回答 1查看 1.4K关注 0票数 0

我有以下样本嵌套的json响应,我需要将此响应与特定值转换为CSV文件。下面是嵌套的Json响应示例:

代码语言:javascript
运行
复制
{
  "transaction": {
    "id": "TestTransID",
    "testCode": "NEW",
    "TestStatus": "SUCCESS",
    "client": {
      "TestNumber": "112112111"
    },
    "subject": {
      "individual": {
        "additionalAttributes": {
          "extraid": "787877878"
        },
        "addressList": [
          {
            "city": "New York",
            "country": {
              "name": "United States"
            },
            "postalCode": "123456789",
            "stateOrProvince": {
              "codeValue": "NY"
            }
          }
        ],
        "gender": "F",
        "identificationDocumentList": [
          {
            "number": "1214558520",
            "type": "TestId"
          }
        ],
        "name": {
          "firstName": "Qusay TestFull",
          "lastName": "TestLast",
          "middleName": "Middle 3"
        }
      }
    },
    "PROCESSConfiguration": {
      "id": 1
    },
    "testProductList": [
      {
        "product": {
          "id": 00,
          "name": "Test PROCESS",
          "productCode": "EFG",
          "disclaimer": "TestDisclaimer"
        },
        "testSourceResponseList": [
          {
            "testSource": {
              "id": 1,
              "name": "TEST"
            },
            "testSourceRecordList": [
              {
                "type": "TestRecord",
                "alertReasonCode": "TESTS",
                "alertReasonDescription": "ACTION LIST HIT - TEST",
                "testSource": "TEST",
                "varListNameFull": "TEST FULL NAME",
                "varListNameShort": "TEST SHORT",
                "varProgList": [
                  "SHORT"
                ],
                "varListId": "3421",
                "subject": {
                  "individual": {
                    "TestScore": {
                      "TestScore": 100,
                      "triggeredRule": "TestRule"
                    },
                    "aNameList": [
                      {
                        "fullName": " TestNameA",
                        "lastName": "TestNameA"
                      },
                      {
                        "firstName": "TestFirst",
                        "fullName": "TestFirst HUSAYN",
                        "lastName": "TestLast"
                      },
                      {
                        "firstName": "TestFirst",
                        "fullName": "TestFull",
                        "lastName": "TestLast"
                      },
                      {
                        "firstName": "TestFirst",
                        "fullName": "TestFull",
                        "lastName": "TestLast"
                      }
                    ],
                    "birthList": [
                      {
                        "dateOfBirth": "12 Apr 1910",
                        "dateOfBirthVerified": "true"
                      }
                    ],
                    "name": {
                      "firstName": "TestFirst",
                      "fullName": "TestFull",
                      "lastName": "TestLast"
                      },
                    "varNationality": [
                      {
                        "verified": "true"
                      }
                    ],
                    "remarks": "remark1"
                  }
                }
              },
              {
                "testSource": "TEST",
                "varListNameFull": "TEST FULL",
                "varListNameShort": "TEST SHORT",
                "varProgList": [
                  "XYZ"
                ],
                "varListId": "1234",
                "subject": {
                  "individual": {
                    "overallScore": {
                      "TestScore": 100,
                      "triggeredRule": "Testing"
                    },
                    "birthList": [
                      {
                        "dateOfBirth": "1965",
                      },
                      {
                        "dateOfBirth": "1966",
                      }
                    ],
                    "name": {
                      "firstName": "TestFirst",
                      "fullName": "TestFull",
                      "lastName": "TestLast",
                    },
                    "varNationality": [
                      {
                        "verified": "true"
                      }
                    ],
                    "remarks": "REMARK2"
                  }
                }
              }
            ]
          }
        ]
      }
    ],
  }
}

我需要从第40行的""PROCESSConfiguration":{ "id":1“获取响应。如果你会把上面的代码放在notepad ++中。

我还需要像名字,姓氏全名,道布等变量值方面的响应。

EN

回答 1

Stack Overflow用户

发布于 2016-07-08 04:58:03

我仍然不确定被要求的是什么。假设您希望JSON文件中的每个元素都有一个完全限定的路径。

我首先对基于http://jsonlint.com/的JSON做了一些小的调整。

在此基础上,我对一个对象进行了概念验证,比如您发布的JSON。它适用于这种情况。我包装了处理多个对象的逻辑,假设一个对象何时开始,下一个对象何时开始。此外,应该添加逻辑来处理包含多个属性(即Get-Process中的线程)的嵌套序列/数组,以处理一般情况。具有一组值的单个元素(如本例中的.transaction.varProgList )是通过在它们之间加上‘;’来处理的。

CSV文件假定所有对象都是对称的(具有相同的属性)。不需要检查每个对象的属性是否与其他对象的属性对齐。注意,嵌套序列的处理与此相关。您可以通过取消对System.Collections.ICollection部分的注释并尝试类似于(Get-Process r*) | Select-Object Name,Threads | Expand-NestedProperty | Out-File .\t.csv -Width 100000的方式来查看此示例

repro如下所示,其中$a是调整后的JSON内容,函数另存为Expand-NestedProperty.ps1。

代码语言:javascript
运行
复制
# Load the function
. .\Expand-NestedProperty.ps1
# Create PowerShell object(s) based on the JSON
$b = $a | ConvertFrom-Json 
# Create a file with the CSV contents. 
$b | Expand-NestedProperty | Out-File -FilePath .\my.csv -Width 100000 

将其另存为Expand-NestedProperty.ps1

代码语言:javascript
运行
复制
function Expand-NestedProperty {
    [CmdletBinding()]
    param (
        [Parameter( Position=0,
                    Mandatory=$true,
                    ValueFromPipeline=$true,
                    ValueFromPipelineByPropertyName=$true,
                    ValueFromRemainingArguments=$false,
                    HelpMessage='Object required...' )]
        $InputObject
    )
    begin {
        function ExpandNestedProperty {
            [CmdletBinding()]
            param (
                [Parameter( Position=0,
                            Mandatory=$true,
                            ValueFromPipeline=$true,
                            ValueFromPipelineByPropertyName=$true,
                            ValueFromRemainingArguments=$false,
                            HelpMessage='Object required...' )]
                $InputObject,
                [Parameter( Position=1,
                            Mandatory=$false,
                            ValueFromPipeline=$false,
                            ValueFromPipelineByPropertyName=$true,
                            ValueFromRemainingArguments=$false,
                            HelpMessage='String required...' )]
                [string]
                $FullyQualifiedName = ""
            )
            begin {
                $localResults =@()
                $FQN = $FullyQualifiedName
                $nestedProperties = $null
            }
            process {
                foreach ($obj in $InputObject.psobject.Properties) {
                    if ($(try {$obj.Value[0] -is [PSCustomObject]} catch {$false})) { # Catch 'Cannot index into a null array' for null values
                        # Nested properties
                        $FQN = "$($FullyQualifiedName).$($obj.Name)"
                        $nestedProperties = $obj.value | ExpandNestedProperty -FullyQualifiedName $FQN
                    }
                    elseif ($obj.Value -is [array]) {
                        # Array property
                        $FQN = "$($FullyQualifiedName).$($obj.Name)"
                        [psobject]$nestedProperties = @{
                            $FQN = ($obj.Value -join ';')
                        }
                    }
                    # Example of how to deal with generic case. 
                    # This needed for the Get-Process values ([System.Collections.ReadOnlyCollectionBase] and [System.Diagnostics.FileVersionInfo]) that are not [array] collection type.
<#
                    elseif ($obj.Value -is [System.Collections.ICollection]) { 
                        # Nested properties
                        $FQN = "$($FullyQualifiedName).$($obj.Name)"
                        $nestedProperties = $obj.value | ExpandNestedProperty -FullyQualifiedName $FQN
                    }
#>
                    else { # ($obj -is [PSNoteProperty]) for this case, but could be any type
                        $FQN = "$($FullyQualifiedName).$($obj.Name)"
                        [psobject]$nestedProperties = @{
                            $FQN = $obj.Value
                        }
                    }
                    $localResults += $nestedProperties
                } #foreach $obj
            }
            end {
                [pscustomobject]$localResults
            }
        } # function ExpandNestedProperty
        $objectNumber = 0
        $firstObject = @()
        $otherObjects = @()
    }
    process {
        if ($objectNumber -eq 0) {
            $objectNumber++
            $firstObject = $InputObject[0] | ExpandNestedProperty
        }
        else {
            if ($InputObject -is [array]) {
                foreach ($nextInputObject in $InputObject[1..-1]) {
                    $objectNumber++
                    $otherObjects += ,($nextInputObject | ExpandNestedProperty)
                }
            }
            else {
                $objectNumber++
                $otherObjects += ,($InputObject | ExpandNestedProperty)
            }
        }
    }
    end {
        # Output CSV header and a line for each object which was the specific requirement here.  
        # Could create an array of objects using $firstObject + $otherObjects that is then piped to Export-CSV if we want a generic case.
        Write-Output "`"$($firstObject.Keys -join '","')`""
        Write-Output "`"$($firstObject.Values -join '","')`""
        foreach ($otherObject in $otherObjects) {
            Write-Output "`"$($otherObject.Values -join '","')`""
        }
    }
} # function Expand-NestedProperty
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38213162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档