-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormat-Json.ps1
More file actions
64 lines (55 loc) · 1.79 KB
/
Format-Json.ps1
File metadata and controls
64 lines (55 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<#
.SYNOPSIS
Formats a JSON string or file with pretty-printing.
.DESCRIPTION
This function takes a JSON string or file path as input and formats it with pretty-printing. If the input is a file path, the file content is read and treated as a JSON string. The formatted JSON is then written to the pipeline.
.PARAMETER InputObject
The JSON string or file path to format.
.EXAMPLE
Format-Json '{"name": "John", "age": 30}'
# Output:
# {
# "name": "John",
# "age": 30
# }
Format-Json -InputObject 'C:\path\to\file.json'
# Output:
# {
# "name": "John",
# "age": 30
# }
echo '{"name": "John", "age": 30}' | Format-Json
# Output:
# {
# "name": "John",
# "age": 30
# }
#>
function Format-Json {
[CmdletBinding()]
param (
[Parameter(Mandatory=$false, Position=0, ValueFromPipeline=$true)]
[string]$InputObject
)
process {
if ($InputObject -and (Test-Path $InputObject)) {
# If the input is a file path and the file exists, read the file content
$jsonString = Get-Content -Path $InputObject -Raw
} else {
# Otherwise, treat the input as a JSON string
$jsonString = $InputObject
}
if (-not $jsonString) {
Write-Error "No input provided or file does not exist."
return
}
try {
# Convert the JSON string to a PowerShell object and then back to a JSON string with pretty-printing
$jsonObject = $jsonString | ConvertFrom-Json
$prettyJson = $jsonObject | ConvertTo-Json -Depth 10
Write-Output $prettyJson
} catch {
Write-Error "Failed to format JSON. Please ensure the input is valid JSON."
}
}
}