Fastest way to flatten / un-flatten nested JSON objects

前端 未结 13 1284
孤城傲影
孤城傲影 2020-11-21 20:32

I threw some code together to flatten and un-flatten complex/nested JSON objects. It works, but it\'s a bit slow (triggers the \'long script\' warning).

For the flat

相关标签:
13条回答
  • 2020-11-21 21:29

    Here's a recursive solution for flatten I put together in PowerShell:

    #---helper function for ConvertTo-JhcUtilJsonTable
    #
    function getNodes {
        param (
            [Parameter(Mandatory)]
            [System.Object]
            $job,
            [Parameter(Mandatory)]
            [System.String]
            $path
        )
    
        $t = $job.GetType()
        $ct = 0
        $h = @{}
    
        if ($t.Name -eq 'PSCustomObject') {
            foreach ($m in Get-Member -InputObject $job -MemberType NoteProperty) {
                getNodes -job $job.($m.Name) -path ($path + '.' + $m.Name)
            }
            
        }
        elseif ($t.Name -eq 'Object[]') {
            foreach ($o in $job) {
                getNodes -job $o -path ($path + "[$ct]")
                $ct++
            }
        }
        else {
            $h[$path] = $job
            $h
        }
    }
    
    
    #---flattens a JSON document object into a key value table where keys are proper JSON paths corresponding to their value
    #
    function ConvertTo-JhcUtilJsonTable {
        param (
            [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
            [System.Object[]]
            $jsonObj
        )
    
        begin {
            $rootNode = 'root'    
        }
        
        process {
            foreach ($o in $jsonObj) {
                $table = getNodes -job $o -path $rootNode
    
                # $h = @{}
                $a = @()
                $pat = '^' + $rootNode
                
                foreach ($i in $table) {
                    foreach ($k in $i.keys) {
                        # $h[$k -replace $pat, ''] = $i[$k]
                        $a += New-Object -TypeName psobject -Property @{'Key' = $($k -replace $pat, ''); 'Value' = $i[$k]}
                        # $h[$k -replace $pat, ''] = $i[$k]
                    }
                }
                # $h
                $a
            }
        }
    
        end{}
    }
    

    Example:

    '{"name": "John","Address": {"house": "1234", "Street": "Boogie Ave"}, "pets": [{"Type": "Dog", "Age": 4, "Toys": ["rubberBall", "rope"]},{"Type": "Cat", "Age": 7, "Toys": ["catNip"]}]}' | ConvertFrom-Json | ConvertTo-JhcUtilJsonTable
    
    Key              Value
    ---              -----
    .Address.house   1234
    .Address.Street  Boogie Ave
    .name            John
    .pets[0].Age     4
    .pets[0].Toys[0] rubberBall
    .pets[0].Toys[1] rope
    .pets[0].Type    Dog
    .pets[1].Age     7
    .pets[1].Toys[0] catNip
    .pets[1].Type    Cat
    
    0 讨论(0)
提交回复
热议问题