Add EscapeHandling parameter in ConvertTo-Json cmdlet (#7775)

Add EscapeHandling parameter in ConvertTo-Json cmdlet to allow escape the HTML (<, >, &, ', ") and control characters (e.g. newline).
This commit is contained in:
Ilya
2018-10-02 10:54:33 +05:00
committed by GitHub
parent d946121d7e
commit d862d4075f
2 changed files with 33 additions and 5 deletions
@@ -2,15 +2,16 @@
// Licensed under the MIT License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Management.Automation;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Globalization;
using Dbg = System.Management.Automation;
using System.Management.Automation;
using System.Management.Automation.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
@@ -73,6 +74,14 @@ namespace Microsoft.PowerShell.Commands
[Parameter]
public SwitchParameter AsArray { get; set; }
/// <summary>
/// Specifies how strings are escaped when writing JSON text.
/// If the EscapeHandling property is set to EscapeHtml, the result JSON string will
/// be returned with HTML (<, >, &, ', ") and control characters (e.g. newline) are escaped.
/// </summary>
[Parameter]
public StringEscapeHandling EscapeHandling { get; set; } = StringEscapeHandling.Default;
#endregion parameters
#region overrides
@@ -125,7 +134,12 @@ namespace Microsoft.PowerShell.Commands
{
return;
}
JsonSerializerSettings jsonSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None, MaxDepth = 1024 };
JsonSerializerSettings jsonSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.None,
MaxDepth = 1024,
StringEscapeHandling = EscapeHandling
};
if (EnumsAsStrings)
{
jsonSettings.Converters.Add(new StringEnumConverter());
@@ -1,6 +1,10 @@
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
Describe 'ConvertTo-Json' -tags "CI" {
BeforeAll {
$newline = [System.Environment]::NewLine
}
It 'Newtonsoft.Json.Linq.Jproperty should be converted to Json properly' {
$EgJObject = New-Object -TypeName Newtonsoft.Json.Linq.JObject
$EgJObject.Add("TestValue1", "123456")
@@ -48,4 +52,14 @@ Describe 'ConvertTo-Json' -tags "CI" {
$output = 1 | ConvertTo-Json
$output | Should -BeExactly '1'
}
It "The result string should <Name>." -TestCases @(
@{name = "be not escaped by default."; params = @{}; expected = "{$newline ""abc"": ""'def'""$newline}" }
@{name = "be not escaped with '-EscapeHandling Default'."; params = @{EscapeHandling = 'Default'}; expected = "{$newline ""abc"": ""'def'""$newline}" }
@{name = "be escaped with '-EscapeHandling EscapeHtml'."; params = @{EscapeHandling = 'EscapeHtml'}; expected = "{$newline ""abc"": ""\u0027def\u0027""$newline}" }
) {
param ($name, $params ,$expected)
@{ 'abc' = "'def'" } | ConvertTo-Json @params | Should -BeExactly $expected
}
}