You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ConvertFrom-Json flattens single-item arrays into objects when opening brace of JSON isn't on first line #18804
When using ConvertFrom-Json to convert a JSON file to a PSCUstomObject, I have run into a weird behavior when the JSON's main object doesn't start on line 1, but instead starts either with a blank line, or a comment (In this case I put a comment there to prevent any trim function to strip the newline, but the result is the same whether or not the first line is a comment or just blank, as long as it isn't {
Take the following JSON file, test.json in the behavior examples below:
// This file contains test data
{
"testArray": [
{
"name": "test"
}
],
"testArray2": [
{
"name": "test2"
},
{
"name": "test3"
}
]
}
And process it with ConvertFrom-Json, you'd expect it to be the same as when processing the following file:
PS>$PSVersionTable
Name Value
---------
PSVersion 7.3.1
PSEdition Core
GitCommitId 7.3.1
OS Microsoft Windows 10.0.22623
Platform Win32NT
PSCompatibleVersions {1.0,2.0,3.0,4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0
To avoid the problem, use Get-Content -Raw in order to pass the entire document as a single string, which not only avoids the ambiguity, but speeds up your command as well.
Activity
mklement0 commentedon Dec 15, 2022
You're seeing the results of an (unfortunate) heuristic built into
ConvertFrom-Json, as previously discussed in:To avoid the problem, use
Get-Content -Rawin order to pass the entire document as a single string, which not only avoids the ambiguity, but speeds up your command as well.