Guest User

Untitled

a guest
Dec 17th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. $script:options = [System.Text.RegularExpressions.RegexOptions]
  2. $script:OpenMatcher = [regex]::new('[\{\[]\s*$', ($options::Compiled -bor $options::ExplicitCapture))
  3.  
  4. function ConvertTo-PrettyJson {
  5. [CmdletBinding(DefaultParameterSetName="withObject",SupportsShouldProcess=$true)]
  6. param (
  7. [parameter(Mandatory,ValueFromPipeline=$true,ParameterSetName="withObject")]
  8. $InputObject,
  9. [parameter(Mandatory,ParameterSetName="withJson")]
  10. [string]
  11. $Json,
  12. [ValidateLength(1, 1)]
  13. [string]
  14. $IndentChar = ' ',
  15. [ValidateRange(1, 20)]
  16. [int]
  17. $IndentWidth = 4
  18. )
  19.  
  20. switch ($PSCmdlet.ParameterSetName) {
  21. "withObject" {
  22. if (! $InputObject) {
  23. return
  24. }
  25. $Json = ConvertTo-Json $InputObject
  26. }
  27. "withJson" {
  28. try {
  29. $Json = ConvertFrom-Json $Json | ConvertTo-Json $Json
  30. }
  31. catch {
  32. throw 'invalid json format: $Json.'
  33. }
  34. }
  35. }
  36.  
  37. if (! $InputObject) { return }
  38.  
  39. # unit indent string
  40. $indent = $IndentChar * $IndentWidth
  41.  
  42. # indent stacks for open and close positions
  43. $indents = @()
  44. $endIndents = @()
  45.  
  46. # current indent
  47. $lastIndent = -1
  48. $closeIndent = -1
  49.  
  50. # real indent count
  51. $indentCount = 0
  52.  
  53. $Json -split "`r?`n" | ? { $_ } -PipelineVariable line | % {
  54. $indentSize = $line -match '^ *' | % { $Matches[0].Length }
  55. switch ($indentSize) {
  56. $lastIndent {
  57. # the same indent from previous line
  58. }
  59. $closeIndent {
  60. # parenthesis closed.
  61. $indents = @($indents | select -Skip 1)
  62. $endIndents = @($endIndents | select -Skip 1)
  63. $lastIndent = $indents[0]
  64. $closeIndent = $endIndents[0]
  65. $indentCount--
  66. }
  67. default {
  68. # new indent size
  69. $lastIndent = $indentSize
  70. $indents = ,$lastIndent + $indents
  71. }
  72. }
  73.  
  74. # out current line.
  75. Write-Output (($indent * $indentCount) + $line.Substring($indentSize))
  76.  
  77. $match = $script:OpenMatcher.Match($line)
  78. if ($match.Success) {
  79. # parenthesis opened.
  80. $closeIndent = $match.Index
  81. $endIndents = ,$closeIndent + $endIndents
  82. $indentCount++
  83. }
  84. } | Out-String
  85. }
Add Comment
Please, Sign In to add comment