I’m using PowerShell and am trying to convert a multi line string value which contains JSON into an object and them convert that PS object to JSON. I’m familiar with converting PowerShell Objects to JSON with single string values.
Below is an example;
# JSON string
$JSONStringValue = @"
"steps": [
{
"name": "Example step",
"collectPageSource": false,
"errorConditions": [],
"actions": [
{
"hello": "everyone"
}
]
}
]
"@
# PS Object with JSON string included
$ObjectToConvertToJson =@{
"Hello123" = $JSONStringValue
}
$ObjectToConvertToJson | ConvertTo-Json
Upon converting the $ObjectToConvertToJson the output I get shows that it’s converted the String value to JSON as well rather than leaving it as a string value only
Output;
{
"Hello123": ""steps": [n {n "name": "Example step",n "collectPageSource": false,n "errorConditions": [],n "actions": [n {n "hello": "everyone"n }n ]n }n]"
}
What do I need to do to retain the String value as a string when converting the object to JSON – or is this even possible?
2
Answers
Having reviewed my code with my manager he spotted that the string value was not a complete JSON object in the string as I had missed off the { }ie
should have been
With the completed JSON in the string in the PowerShell Object convert from JSON
and in the main Body to POST back to the API convert the entire object to JSON I.E
No, it is not possible to retain the string in its original form, because string values in JSON require certain characters to be escaped, and you’re seeing the results of that; notably, literal newlines aren’t permitted and must be represented with escape sequence
n
However, the JSON-encoded form of a string is equivalent to the string in its original form, and if you decode it – such as via
ConvertFrom-Json
– you’ll get the original form of the string back.Example:
Define an object with a string property whose value requires escaping – (note that what the content of the string represents – whether nested JSON or something else – is irrelevant).
The lines end in a space by design, to better visualize how newlines are encoded later.
A here-string is used to define the string value.
Now convert the object to JSON and display the result:
Output – note how the newlines are escaped as
n
, and"
andas
"
and\
, respectively:Now convert the JSON representation back to an object, which involves decoding the
"String"
property value back into a verbatim .NET string with the original format (Format-List
is used to ensure that the multiline string displays in full):Output: