Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging json objects in powershell

Tags:

People also ask

How do I merge two JSON objects?

JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.

Can PowerShell parse JSON?

PowerShell is a great tool to use for manipulating JSON which is used throughout Azure. Have fun scripting! Additional reading: 7.1: ConvertFrom-Json (Microsoft.

Can a JSON file contain multiple objects?

The file is invalid if it contains more than one JSON object. When you try to load and parse a JSON file with multiple JSON objects, each line contains valid JSON, but as a whole, it is not a valid JSON as there is no top-level list or object definition.


I have json that looks like this:

{
    "Workflow": [
        {
            "Parameters": {
                "Project": "/Path/To/File",
                "OtherParam": "True"
            }
        }
    ],
    "Overrides": [
        {
            "Special": {
                "Parameters": {
                    "NewParam": "NewStuffGoesHere",
                    "OtherParam": "False"
                }
            }
        }
    ]
}

... where I want to use the Overrides.Special section to add or update fields in the workflow object. In other words, given the json above, I want to do something like this:

$config = Get-Content workflow.json | out-string | ConvertFrom-Json
$configWithOverrides = Merge-Object $config.Workflow $config.Overrides.Special

And end up with something like this:

$configWithOverrides

Parameters
----------
@{Project=/Path/To/File; NewParam=NewStuffGoesHere; OtherParam=False}

I can certainly write the Merge-Object function above to add or update values as needed based on what's in the override section, but it seems there should (could?) be a built-in or one-liner way to handle this.

I tried this:

$test = $config.Workflow + $config.Overrides.Special

...but that doesn't quite work.

$test
Parameters
----------
@{Project=/Path/To/File; OtherParam=True}
@{NewParam=NewStuffGoesHere; OtherParam=False}

This enables adding parameters:

>$test.Parameters.NewParam
NewStuffGoesHere

...but it's not so great for updating them

>$test.Parameters.OtherParam
True
False

Note - in this example, I'm choosing to handle the merge after converting the json to a psobject, but that's not a requirement.