Forum Discussion

vivek10688's avatar
vivek10688
Copper Contributor
Jul 20, 2022
Solved

How to add a new set of key & values in json file.

Problem Statement: I want to add a set of new key & value in existing parsed Json after specific index. or position. For example: I have imported Json in $Json variable and then I wanted to add new s...
  • LainRobertson's avatar
    Jul 22, 2022

    vivek10688 

     

    Can you provide us with an original example (i.e. before the script is called) of the file you're reading from on line 2?

     

    There are a few things that don't make sense in the first output example when compared to how the script is written. Having the original example/JSON template will help.

     

    In short though, you'd ideally want to work with the List type.

     

    One thing you don't want to be doing is constantly reading from and writing to the file every iteration of the loop, as the current script does. That will scale very, very poorly as the object count goes up, so unless you're working with a very small data set, I'd be avoiding this approach.

     

    Here's a somewhat abstract example - given the above caveats - using the List approach.

     

    Bogus JSON template used

    {
    	"Environment": {},
    	"Profiles": {
    		"Services": [
    			{
    				"Name": "A"
    			},
    			{
    				"Name": "B"
    			},
    			{
    				"Name": "C"
    			},
    			{
    				"Name": "D"
    			},
    			{
    				"Name": "E"
    			},
    			{
    				"Name": "F"
    			}
    		]
    	}
    }

     

    Conceptual code only

    $JsonObjects = Get-Content .\forum.json | ConvertFrom-Json;
    $ServicesObjects = [System.Collections.Generic.List[PSCustomObject]]$Data.Profiles.Services;
    $ServicesObjects.FindIndex({ param($Entry); $Entry.Name.Equals("E") });
    $ServicesObjects.Insert($ServicesObjects.FindIndex({ param($Entry); $Entry.Name.Equals("E") }), ([PSCustomObject] @{ Name = "WhateverYouLike"; }));

     

    This conceptual code is purely to demonstrate how to work with the List type. It is not a complete solution to your question.

     

    Here's the output from this conceptual example.

     

    Once you've finished inserting items wherever you want them, you can then re-assign the List object back onto the broader JSON data set from where you obtained it and push that back out to JSON using the usual ConvertTo-Json commandlet, after which you can dump it back to file or do whatever you want to do.

     

    $Data.Profiles.Services = $ServicesObjects;
    $Data | ConvertTo-Json;

     

     

    Cheers,

    Lain

Resources