How do I extract JSON items without changing the schema of the extracted item.

Steve Lundy 21 Reputation points
2022-11-19T02:21:45.93+00:00

Hi all,

I am new to PowerShell scripting, and I am having an issue.

I have created the following powershell script to extract given JSON items out of a JSON file, and dump them into a separate file. The script is as follows:

262034-image.png

This works fine, when I have flat JSON item for example:
262086-image.png

The problem comes in when the JSON item is a little more complex:
This:
262066-image.png

after it is extracted becomes this:
262087-image.png

I'm wondering if there is a way to retain the original format for the attachmentList portion of the JSON object. As the way it is now, application that consumes the data doesn't like this new format.

If anyone has any suggestions, I would greatly appreciate it.

Thanks in Advance,

Steve

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,388 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,096 Reputation points
    2022-11-19T20:20:47.55+00:00

    The ConvertTo-Json only expands, by default, the input object to a depth of 2. Anything deeper than that is expressed as the data type in the PSCustomObject.

    Add the parameter "-Depth" to the ConvertTo-Json cmdlet using a suitable value. If you have a reasonably uncomplicated structure, try a value of 10 to start.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Steve Lundy 21 Reputation points
    2022-11-20T00:16:53.063+00:00

    Hi Rich,

    It took a little bit, but I figured out what your answer meant. Before I could use the -Depth option, I had to download and install Powershell 7.3 on my desktop. The version of Powershell I was using was 5.1, where that option was not available.

    I had to make two changes to my scripts, first to my powershell script, I added the -Depth option:
    $fileNameParameter = $args[0]
    $ItemToExtract = $args[1]

    (Get-Content $fileNameParameter | ConvertFrom-Json).item | ? {$_.'Integrity ID' -eq $ItemToExtract } | ConvertTo-Json -Depth 10 | Out-File -Append .\extractedJSON.json

    Add-Content -Path .\extractedJSON.json -Value ","

    The second part was in my calling windows batch script, I had to update it to ensure that it used the new pwsh.exe command as opposed to powershell.exe:

    pwsh.exe -File ExtractSingleJSONObject.ps1 %JSONSOURCEFILE% %%~a

    Thanks for your help Rich