Skip to content

Instantly share code, notes, and snippets.

@mdnmdn
Last active January 2, 2022 14:10
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mdnmdn/6936714 to your computer and use it in GitHub Desktop.
Save mdnmdn/6936714 to your computer and use it in GitHub Desktop.
ConvertTo-JSON for Powershell 2.0
function Escape-JSONString($str){
if ($str -eq $null) {return ""}
$str = $str.ToString().Replace('"','\"').Replace('\','\\').Replace("`n",'\n').Replace("`r",'\r').Replace("`t",'\t')
return $str;
}
function ConvertTo-JSON($maxDepth = 4,$forceArray = $false) {
begin {
$data = @()
}
process{
$data += $_
}
end{
if ($data.length -eq 1 -and $forceArray -eq $false) {
$value = $data[0]
} else {
$value = $data
}
if ($value -eq $null) {
return "null"
}
$dataType = $value.GetType().Name
switch -regex ($dataType) {
'String' {
return "`"{0}`"" -f (Escape-JSONString $value )
}
'(System\.)?DateTime' {return "`"{0:yyyy-MM-dd}T{0:HH:mm:ss}`"" -f $value}
'Int32|Double' {return "$value"}
'Boolean' {return "$value".ToLower()}
'(System\.)?Object\[\]' { # array
if ($maxDepth -le 0){return "`"$value`""}
$jsonResult = ''
foreach($elem in $value){
#if ($elem -eq $null) {continue}
if ($jsonResult.Length -gt 0) {$jsonResult +=', '}
$jsonResult += ($elem | ConvertTo-JSON -maxDepth ($maxDepth -1))
}
return "[" + $jsonResult + "]"
}
'(System\.)?Hashtable' { # hashtable
$jsonResult = ''
foreach($key in $value.Keys){
if ($jsonResult.Length -gt 0) {$jsonResult +=', '}
$jsonResult +=
@"
"{0}": {1}
"@ -f $key , ($value[$key] | ConvertTo-JSON -maxDepth ($maxDepth -1) )
}
return "{" + $jsonResult + "}"
}
default { #object
if ($maxDepth -le 0){return "`"{0}`"" -f (Escape-JSONString $value)}
return "{" +
(($value | Get-Member -MemberType *property | % {
@"
"{0}": {1}
"@ -f $_.Name , ($value.($_.Name) | ConvertTo-JSON -maxDepth ($maxDepth -1) )
}) -join ', ') + "}"
}
}
}
}
#"a" | ConvertTo-JSON
#dir \ | ConvertTo-JSON
#(get-date) | ConvertTo-JSON
#(dir \)[0] | ConvertTo-JSON -maxDepth 1
#@{ "asd" = "sdfads" ; "a" = 2 } | ConvertTo-JSON
Copy link

ghost commented Jan 13, 2017

Hi, This function works totally fine with me, But the problem is it is breaking the order of the elements in the JSON file being sorted alphabetically. So by running the following:
@{ "xx" = "sdfads" ; "a" = 2 } | ConvertTo-JSON

the result becoming:
{ "a": 2, "xx": "sdfads"}

So the original order xx,a is becoming a,xx
How to not sort the order of the elements? Can you suggest what I might need to change?

@mappu
Copy link

mappu commented Jan 31, 2017

What license is this snippet available under?

@jambonmcyeah
Copy link

does anyone know if there's a convertfrom-json implementation just like this one?

@Aaron-Ritter-IDEXX
Copy link

Aaron-Ritter-IDEXX commented May 4, 2018

It seems to me that line 36 doesn't support enough numeric types. I prefer to remove lines 36 and 37 and insert these two lines at line 30, instead:

if ($value.GetType().Name -eq 'Boolean') {return "$value".ToLower()}
if ($value.GetType().IsPrimitive) {return "$value"}

@EliteLoser
Copy link

This is crap. For a solution from a superior mind, see https://github.com/EliteLoser/ConvertTo-Json - but thanks for sharing.

@NaziMeh
Copy link

NaziMeh commented Aug 28, 2018

Hello
how can i remove \t in json?
{\t"id": "63304D56-6A42-43DB-7670-B73FD8389E6", \t"type": "Hello"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment