Skip to content

Commit

Permalink
feat: Import-JSON (Fixes #725)
Browse files Browse the repository at this point in the history
  • Loading branch information
James Brundage committed Nov 23, 2023
1 parent b4d1033 commit 0f3e5f5
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Commands/JSON/Export-Json.ps.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ function Export-Json {

$FileSplat = [Ordered]@{}

if ($path) { $FileSplat['Path'] = $path; $path }
elseif ($literalPath) { $FileSplat['LiteralPath'] = $path; $literalPath }
if ($path) { $FileSplat['Path'] = $path;}
elseif ($literalPath) { $FileSplat['LiteralPath'] = $literalPath; }

if ((-not $Force) -and $NoClobber) {
if ((Test-Path @fileSplat) -and -not $Force) {
Expand Down
59 changes: 59 additions & 0 deletions Commands/JSON/Import-JSON.ps.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
function Import-JSON
{
<#
.SYNOPSIS
Imports JSON
.DESCRIPTION
Imports json files and outputs PowerShell objects
.PARAMETER LiteralPath
Specifies the path to the XML files.
Unlike Path , the value of the LiteralPath parameter is used exactly as it's typed.
No characters are interpreted as wildcards.
If the path includes escape characters, enclose it in single quotation marks.
Single quotation marks tell PowerShell not to interpret any characters as escape sequences.
.PARAMETER Path
Specifies the path to the XML files.
.PARAMETER First
Gets only the specified number of objects. Enter the number of objects to get.
.PARAMETER Skip
Ignores the specified number of objects and then gets the remaining objects. Enter the number of objects to skip.
#>
[Inherit("Import-Clixml",Abstract,ExcludeParameter='IncludeTotalCount')]
[CmdletBinding(SupportsPaging)]
param(
# The delimiter between objects.
# If a delimiter is provided, the content will be split by this delimeter.
[vbn()]
[string]
$Delimiter
)

process {
$FileSplat = [Ordered]@{}

if ($path) { $FileSplat['Path'] = $path}
elseif ($literalPath) { $FileSplat['LiteralPath'] = $path = $literalPath }

$fileContent = Get-Content @FileSplat -Raw
if (-not $fileContent) { return }

if ($Delimiter) {
foreach ($delimitedSegment in
$fileContent -split "(?<=[\]\}])$([Regex]::Escape($Delimiter))(?=[\[\{])"
) {
try {
$delimitedSegment | ConvertFrom-Json
} catch {
Write-Error "'$($path)': $($_.Exception.Message)" -TargetObject $delimitedSegment
}
}
} else {
try {
$fileContent | ConvertFrom-Json
} catch {
Write-Error "'$($path)': $($_.Exception.Message)" -TargetObject $fileContent
return
}
}
}
}

0 comments on commit 0f3e5f5

Please sign in to comment.