Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a JSON file and convert it to an object of a specific type?

I have a type FooObject and I have a JSON file which was serialized from a FooObject instance. Now I want to use ConvertFrom-Json to load the JSON file to memory and covert the output of the command to a FooObject object, and then use the new object in a cmdlet Set-Bar which only accept FooObject as the parameter type.

But I notice that the output type of ConvertFrom-Json is PSCustomObject and I did not find any way to convert PSCustomObject to FooObject.

like image 598
NonStatic Avatar asked Mar 08 '16 09:03

NonStatic


People also ask

How do I convert a JSON file to an object?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.

How do you convert a JSON Request into respective class object?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

How do you load a JSON object in Python?

The load()/loads() method is used for it. If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load()/loads(), which is usually used to load from string, otherwise, the root object is in list or dict. See the following table given below. json.


2 Answers

Try casting the custom object to FooObject:

$foo = [FooObject](Get-Content 'C:\path\to\your.json' | Out-String | ConvertFrom-Json) 

If that doesn't work, try constructing the FooObject instance with the properties of the input object (provided the class has a constructor like that):

$json = Get-Content 'C:\path\to\your.json' | Out-String | ConvertFrom-Json $foo = New-Object FooObject ($json.Foo, $json.Bar, $json.Baz) 

If that also doesn't work you need to create an empty FooObject instance and update its properties afterwards:

$json = Get-Content 'C:\path\to\your.json' | Out-String | ConvertFrom-Json $foo = New-Object FooObject $foo.AA = $json.Foo $foo.BB = $json.Bar $foo.CC = $json.Baz 
like image 82
Ansgar Wiechers Avatar answered Oct 05 '22 11:10

Ansgar Wiechers


Based on PowerTip: Convert JSON File to PowerShell Object, you can do the following:

Get-Content -Raw -Path <jsonFile>.json | ConvertFrom-Json 
like image 41
thatOneGuy Avatar answered Oct 05 '22 12:10

thatOneGuy