How to remove special chars in JSON file format
Sometimes you want to write out an object in JSON format to a file. This is fine and what you would normally use ConvertTo-Json for.
The only issue is the generated JSON will convert some chars like < to \u003c which is not ideal for your JSON output. This seems to be a limitation with the PowerShell command.
To fix this, use this Regex snippet below to replace the escaped tokens in your output to make the file more readable.
1
$data | ConvertTo-Json -Depth 10 | ForEach-Object { [Regex]::Replace($_, "\\u(?<Value>[a-zA-Z0-9]{4})", { param($m) ([char]([int]::Parse($m.Groups['Value'].Value, [System.Globalization.NumberStyles]::HexNumber))).ToString() } )} | Out-File $OutputFilename -Force
Copied!
This will turn your output from:
1
"Key": "WLSProtocol",
2
"Values": {
3
"Test": "\u003chttpsTransport maxReceivedMessageSize=\"1255360\"/\u003e",
4
"Staging": "\u003chttpsTransport maxReceivedMessageSize=\"1255360\"/\u003e",
5
"Production": "\u003chttpsTransport maxReceivedMessageSize=\"1255360\"/\u003e"
6
}
Copied!
to
1
"Key": "WLSProtocol",
2
"Values": {
3
"Test": "<httpsTransport maxReceivedMessageSize=\"1255360\"/>",
4
"Staging": "<httpsTransport maxReceivedMessageSize=\"1255360\"/>",
5
"Production": "<httpsTransport maxReceivedMessageSize=\"1255360\"/>",
6
}
Copied!
Note: you still will need to escape some chars like " and \ but these are more managable.
Copy link