-
Notifications
You must be signed in to change notification settings - Fork 0
🚀 Add Export-Json function for exporting JSON data to files #8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
9cb3301
Initial plan
Copilot f90af51
Implement Export-Json function with comprehensive tests and examples
Copilot c30c2ce
Update Export-Json defaults: Depth=2 and Encoding=UTF8NoBOM as requested
Copilot 76d8efc
Add test for array export as root JSON structure
Copilot 1f501f1
Fix linting issue: Replace '| Out-Null' with '$null = ...' pattern
Copilot 9d0633d
Fix linting issues: Remove trailing whitespace, align assignments, an…
Copilot 43417c3
Add comprehensive tests for Export-Json error handling scenarios
Copilot 00f4907
Fix Export-Json test failures: WhatIf behavior and access denied scen…
Copilot 5326be1
Fix Windows compatibility: Replace IsReadOnly with ACL-based permissi…
Copilot f294073
Update IndentationSize default to 2 and improve path resolution reada…
Copilot d5deb45
Fix trailing whitespace in Export-Json.ps1
Copilot 7a35b0d
Simplify path resolution: Use Test-Path directly and resolve path onc…
Copilot f94c462
Improve path resolution: Use Test-Path and Resolve-Path for better re…
Copilot 8c86612
Clean up accidental test file commit and update .gitignore
Copilot 0272237
Update Format-Json test data to use 2-space indentation as new default
Copilot abea97a
Remove placeholder support from Export-Json function
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,3 +16,6 @@ outputs/* | |
| bin/ | ||
| obj/ | ||
| libs/ | ||
|
|
||
| # Test files | ||
| test-*.json | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,170 @@ | ||
| function Export-Json { | ||
| <# | ||
| .SYNOPSIS | ||
| Exports JSON data to a file. | ||
|
|
||
| .DESCRIPTION | ||
| Converts PowerShell objects to JSON format and writes them to one or more files. | ||
| Supports various formatting options including indentation types, sizes, and compact output. | ||
| Can accept both PowerShell objects and JSON strings as input. | ||
|
|
||
| .EXAMPLE | ||
| Export-Json -InputObject $myObject -Path 'output.json' | ||
|
|
||
| Exports a PowerShell object to output.json with default formatting. | ||
|
|
||
| .EXAMPLE | ||
| Export-Json -InputObject $data -Path 'config.json' -IndentationType Spaces -IndentationSize 2 | ||
|
|
||
| Exports data to config.json with 2-space indentation. | ||
|
|
||
| .EXAMPLE | ||
| Export-Json -JsonString $jsonText -Path 'data.json' -Compact | ||
|
|
||
| Exports a JSON string to data.json in compact format. | ||
|
|
||
| .EXAMPLE | ||
| $objects | Export-Json -Path 'output.json' | ||
|
|
||
| Exports multiple objects to the same file via pipeline (last object overwrites). | ||
|
|
||
| .EXAMPLE | ||
| Export-Json -InputObject $config -Path 'settings.json' -IndentationType Tabs -Force | ||
|
|
||
| Exports configuration to settings.json with tab indentation, overwriting if it exists. | ||
|
|
||
| .LINK | ||
| https://psmodule.io/Json/Functions/Export-Json/ | ||
| #> | ||
|
|
||
| [CmdletBinding(DefaultParameterSetName = 'FromObject', SupportsShouldProcess)] | ||
| param ( | ||
| # PowerShell object to convert and export as JSON. | ||
| [Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'FromObject')] | ||
| [PSObject]$InputObject, | ||
|
|
||
| # JSON string to export to file. | ||
| [Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'FromString')] | ||
| [string]$JsonString, | ||
|
|
||
| # The path to the output JSON file. | ||
| [Parameter(Mandatory)] | ||
| [string]$Path, | ||
|
|
||
| # Produce compact (minified) output. | ||
| [Parameter()] | ||
| [switch]$Compact, | ||
|
|
||
| # Indentation type: 'Spaces' or 'Tabs'. | ||
| [Parameter()] | ||
| [ValidateSet('Spaces', 'Tabs')] | ||
| [string]$IndentationType = 'Spaces', | ||
|
|
||
| # Number of spaces or tabs per indentation level. Only used if not compacting. | ||
| [Parameter()] | ||
| [UInt16]$IndentationSize = 2, | ||
|
|
||
| # The maximum depth to serialize nested objects. | ||
| [Parameter()] | ||
| [int]$Depth = 2, | ||
|
|
||
| # Overwrite existing files without prompting. | ||
| [Parameter()] | ||
| [switch]$Force, | ||
|
|
||
| # Text encoding for the output file. | ||
| [Parameter()] | ||
| [ValidateSet('ASCII', 'BigEndianUnicode', 'BigEndianUTF32', 'OEM', 'Unicode', 'UTF7', 'UTF8', 'UTF8BOM', 'UTF8NoBOM', 'UTF32')] | ||
| [string]$Encoding = 'UTF8NoBOM' | ||
| ) | ||
|
|
||
| begin { | ||
| } | ||
|
|
||
| process { | ||
| try { | ||
| # Determine the input object | ||
| $objectToExport = if ($PSCmdlet.ParameterSetName -eq 'FromString') { | ||
| $JsonString | ConvertFrom-Json -Depth $Depth -ErrorAction Stop | ||
| } else { | ||
| $InputObject | ||
| } | ||
|
|
||
| # Generate the file path | ||
| $outputPath = $Path | ||
|
|
||
| # Resolve the path for consistent operations and error messages | ||
| if (Test-Path -Path $outputPath) { | ||
| $resolvedPath = Resolve-Path -Path $outputPath | ||
| } else { | ||
| # For non-existing files, resolve the parent directory and combine with filename | ||
| $parentPath = Split-Path -Path $outputPath -Parent | ||
| $fileName = Split-Path -Path $outputPath -Leaf | ||
| if ($parentPath -and (Test-Path -Path $parentPath)) { | ||
| $resolvedParent = Resolve-Path -Path $parentPath | ||
| $resolvedPath = Join-Path -Path $resolvedParent -ChildPath $fileName | ||
| } else { | ||
| # If parent doesn't exist either, use the original path as-is for error messages | ||
| $resolvedPath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($outputPath) | ||
| } | ||
| } | ||
|
|
||
| # Check if file exists and handle accordingly | ||
| if ((Test-Path -Path $resolvedPath -PathType Leaf) -and -not $Force) { | ||
| if ($PSCmdlet.ShouldProcess($resolvedPath, "Overwrite existing file")) { | ||
| # Continue with export | ||
| } else { | ||
| # Only error if not WhatIf - WhatIf should just show what would happen | ||
| if (-not $WhatIfPreference) { | ||
| Write-Error "File already exists: $resolvedPath. Use -Force to overwrite." | ||
| } | ||
| return | ||
| } | ||
| } | ||
|
|
||
| # Create directory if it doesn't exist | ||
| $directory = Split-Path -Path $resolvedPath -Parent | ||
| if ($directory -and -not (Test-Path -Path $directory -PathType Container)) { | ||
| Write-Verbose "Creating directory: $directory" | ||
| $null = New-Item -Path $directory -ItemType Directory -Force | ||
| } | ||
|
|
||
| # Format the JSON | ||
| if ($Compact) { | ||
| $formattedJson = $objectToExport | ConvertTo-Json -Depth $Depth -Compress | ||
| } else { | ||
| # Use Format-Json for consistent formatting | ||
| $formattedJson = Format-Json -InputObject $objectToExport -IndentationType $IndentationType -IndentationSize $IndentationSize | ||
| } | ||
|
|
||
| # Write to file | ||
| if ($PSCmdlet.ShouldProcess($resolvedPath, "Export JSON")) { | ||
| Write-Verbose "Exporting JSON to: $resolvedPath" | ||
|
|
||
| $writeParams = @{ | ||
| Path = $resolvedPath | ||
| Value = $formattedJson | ||
| Encoding = $Encoding | ||
| } | ||
|
|
||
| # Only use Force for Set-Content if user explicitly requested it | ||
| if ($Force) { | ||
| $writeParams['Force'] = $true | ||
| } | ||
|
|
||
| Set-Content @writeParams -ErrorAction Stop | ||
|
|
||
| # Output file info object | ||
| Get-Item -Path $resolvedPath | Add-Member -MemberType NoteProperty -Name 'JsonExported' -Value $true -PassThru | ||
| } | ||
| } catch [System.ArgumentException] { | ||
| Write-Error "Invalid JSON format: $_" | ||
| } catch [System.IO.DirectoryNotFoundException] { | ||
| Write-Error "Directory not found or could not be created: $directory" | ||
| } catch [System.UnauthorizedAccessException] { | ||
| Write-Error "Access denied: $resolvedPath" | ||
| } catch { | ||
| Write-Error "Failed to export JSON to '$resolvedPath': $_" | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.