Best way to add JSON object to another

Welcome Forums General PowerShell Q&A Best way to add JSON object to another

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
2 years ago.

  • Author
    Posts
  • #62485

    Participant
    Points: 57
    Rank: Member

    I'm struggling with the right way to add an object retrieved from json to a custom object.

    What I want to be able to do is add this custom object and set the value for Enabled to $true in some instances and other instances set it to $false. I need to replicate this task many times and then repost it with the values I want in the task sequence I need. (This is for TFS 2015 r3 release tasks.)
    The issue is when I have the same object $tasks2add[0] added more than once in my new object and I change the value of enabled to either true or false it resets all the previous ones I added to my custom object to the same value.

    I've tried using several differnt methods of adding and I cannot seem to find the on that doesn't seem to make a reference to the value rather than an explicitly copying the object from the json source.

    My sample code is in this gist:

  • #62490

    Participant
    Points: 0
    Rank: Member

    Hello! You should copy your object with all its properties, not just referencing the properties.
    Replace these lines:

    $newArraylist.Add((New-object pscustomobject ($tasks2add[0])))
    $newArraylist.Add((New-object pscustomobject ($tasks2add[1])))
    $newArraylist.Add((New-object pscustomobject ($tasks2add[0])))
    $newArraylist.Add((New-object pscustomobject ($tasks2add[1])))

    With these:

    $newArraylist.Add($tasks2add[0].PSObject.Copy())
    $newArraylist.Add($tasks2add[1].PSObject.Copy())
    $newArraylist.Add($tasks2add[0].PSObject.Copy())
    $newArraylist.Add($tasks2add[1].PSObject.Copy())

    And voilà! It works.

  • #62556

    Participant
    Points: 57
    Rank: Member

    Thank you Nimms Great Tip thank you very much... Much Appreciated.

The topic ‘Best way to add JSON object to another’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort