The following code
$str = '{"attrs": { "c1": "abc", "c2": 123}}'
$json = $str | ConvertFrom-Json
$json.attrs | Get-Member -MemberType Properties | % { echo $_.GetType() }
returns
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False MemberDefinition System.Object
True False MemberDefinition System.Object
Why it doesn't tell if the properties have the data type of string
or int
?
I want to tell if the property has the data type of string. So I can wrap the str values with "
when creating a CSV string.
($json.attrs
| Get-Member -MemberType Properties
| % { if (it's str) { return "`"$_`"" } else { $_ }
) -join ','
CodePudding user response:
To answer your question as asked:
Use the intrinsic psobject
property to reflect on a given object's properties:
$json.attrs.psobject.Properties.Value | ForEach-Object GetType
To test a given property for being of a specific type:
$propName = 'c1'
$json.attrs.$propName -is [string] # -> $true
However, as Santiago Squarzon points out:
For exporting the parsed-from-JSON data to CSV, you don't need to know the data type of the properties, given that (a) CSV is invariably an untyped, text-only format and (b) PowerShell's Export-Csv
cmdlet by default encloses field values in "..."
.