Extend JSON with another in PowerShell

Is there an easy way to expand one JSON file to another and save the output to another file using PowerShell? I'm currently trying to write a repeating function that will allow me to do this *, but maybe there is a simpler solution?

* PSCustomObject over JSON properties converted to PSCustomObject and replace them if necessary (actually check my answer below )

Edit: I need to do something similar to what jquery.extend does, my input:

 { "name": "Some name", "value": 1, "config": { "debug": false, "output": "c:\\" } } 

and

 { "value": 2, "config": { "debug": true }, "debug": { "log": true } } 

And my conclusion should be:

 { "name": "Some name", "value": 2, "config": { "debug": true, "output": "c:\\" }, "debug": { "log": true } } 

PS As a rule, I need to write a script that can be run from a batch file and does not require third-party libraries (limited by Windows resources). I tried my luck with JavaScript Cscript, but I decided not to use it when I found out that the only built-in method for parsing JSON is to evaluate it.

+4
json powershell
source share
2 answers

After a lot of trial and error, I managed to write my current function.

 function ExtendJSON($base, $ext) { $propNames = $($ext | Get-Member -MemberType *Property).Name foreach ($propName in $propNames) { if ($base.PSObject.Properties.Match($propName).Count) { if ($base.$propName.GetType().Name -eq "PSCustomObject") { $base.$propName = ExtendJSON $base.$propName $ext.$propName } else { $base.$propName = $ext.$propName } } else { $base | Add-Member -MemberType NoteProperty -Name $propName -Value $ext.$propName } } return $base } $file1 = (Get-Content $args[0]) -join "`n" | ConvertFrom-Json $file2 = (Get-Content $args[1]) -join "`n" | ConvertFrom-Json #Out-File produces incorrect encoding #ExtendJSON $file1 $file2 | ConvertTo-Json | Out-File $args[2] $output = ExtendJSON $file1 $file2 | ConvertTo-Json #Save output as BOMless UTF8 [System.IO.File]::WriteAllLines($args[2], $output) 

I have no idea if this is the easiest way to achieve my goal, but it really does its job. This also doubles as an answer to the question of how to merge \ merge \ merge two PSCustomObject s that no one seems to have asked yet (maybe I'm breaking open doors here). I am almost inclined to rewrite the question as such, but my question tells me that there may be different methods for extending JSON using PowerShell, which do not necessarily require converting my JSON files to PSCustomObject .

+6
source share

If you use PowerShell 3.0 or higher, you can use the built-in ConvertFrom-Json \ ConvertTo-Json .

If you are stuck in PS 2.0, see Convert a PowerShell project and JSON or this module .

0
source share

All Articles