4

In a PowerShell script, I have some custom data structure that contains Xml in string properties.

When I convert my data structure, useless encoding make the result difficult to read and write (json file used by my script may be manually adapted to match customer requirements before use).

Ex:

"<" | ConvertTo-Json

Returns :

"\u003c"

As far as I know, the < is perfectly valid within a json string.

  1. Why Convertto-Json encode these character ?
  2. Is there a way to avoid it ?

As a comparison, this code:

[System.Reflection.Assembly]::LoadWithPartialName("Newtonsoft.Json")
[Newtonsoft.Json.JsonConvert]::SerializeObject("<")

outputs:

"<"

But this solution relies on a 3rd party library and requires to ship it with my script (which are intended to be distributed to various customer environments).

Steve B
  • 36,818
  • 21
  • 101
  • 174
  • Why is "\u003c" not usable for you? – ArcSet Aug 31 '17 at 15:10
  • 2
    `ConvertTo-Json` uses the [`JavaScriptDeserializer`](https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer(v=vs.110).aspx) class. As microsoft is not popular for making good decisions at browser technologies... Well, there might be your reason for that mess ;) – Clijsters Aug 31 '17 at 15:29
  • @ArcSet: actually, it works as expected. The `ConvertFrom-Json` can read these caracters. However, the files may be manually tweaked before use... having this unicode mess make it very difficult to manipulate. – Steve B Aug 31 '17 at 16:12
  • 1
    Why not do this? `"<>"| ConvertTo-Json | %{ $_.replace("\u003c","<").replace("\u003e",">")}` – ArcSet Aug 31 '17 at 17:19
  • 1
    see... https://stackoverflow.com/questions/32959431/json-file-to-powershell-and-back-to-json-file – Avshalom Aug 31 '17 at 20:05

0 Answers0