Home:ALL Converter>How to convert a JSON string to PSObject?

How to convert a JSON string to PSObject?

Ask Time:2020-02-26T21:42:57         Author:Alex_P

Json Formatter

I want to write a PowerShell function in C#. During the process I receive a string with JSON content. My sample json content is:

string json = "{'TestNr':{'Name':'CSHARP', 'Description':'Test Descriptiopn'}}"

This string should be converted to a PSObject just like ConvertFrom-Json would do.

I was trying to create an object with below lines. It works but it would require a lot of manual scripting especially if the JSON string becomes longer.

PSObject obj = new PSObject();
obj.Properties.Add(new PSNoteProperty("Head", "Children"));

I tried also the below line:

obj = (PSObject)TypeDescriptor.GetConverter(typeof(PSObject)).ConvertFromString(json);

For this I get however the error (I run the function in PowerShell 7):

TypeConverter cannot convert from System.String.

Author:Alex_P,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60415302/how-to-convert-a-json-string-to-psobject
yy