Home > Back-end >  Adding a substring in powershell
Adding a substring in powershell

Time:09-23

I import a csv file in powershell with this code:

import-csv "input.csv" | ConvertTo-Json | Add-Content -Path "output.json"

My output:

{
 "users": [
     {
       "firstName": "name1",
       "lastName": "lastname1",
     }
     {
       "firstName": "name2",
       "lastName": "lastname2",
     }
}

The csv file look like this:

firstname,lastname
name1,lastname1
name2,lastname2

But I need to ad a extra column called "roles" with sub content (I dont know what its called). It should be after lastname, but still part of the users object and in every entry.

"roles" [
    "role1",
    "role2"
   ]

CodePudding user response:

If it's just static data you can use a calculated property to add another column.

Import-Csv -Path "input.csv" | 
Select-Object -Property *, @{Name = 'roles'; Expression = {'StaticData'} } |
ConvertTo-Json | 
Add-Content -Path "output.json"

Assumed your CSV would look like this:

$CSV = @'
firstname,lastname,roles
name1,lastname1,role1
name2,lastname2,role2
'@ | 
ConvertFrom-Csv

And you convert it like this:

$CSV | ConvertTo-Json

The result would be this:

[
  {
    "firstname": "name1",
    "lastname": "lastname1",       
    "roles": "role1"
  },
  {
    "firstname": "name2",
    "lastname": "lastname2",       
    "roles": "role2"
  }
]

CodePudding user response:

Add-Member is a somewhat slow method but viable...

$json = ConvertFrom-Json @'
{
    "users": [{
            "firstName": "name1",
            "lastName": "lastname1"
        },
        {
            "firstName": "name2",
            "lastName": "lastname2"
        }
    ]
}
'@
 
$json.users | Add-Member -MemberType NoteProperty -Name Roles -Value 'empty'

$json | ConvertTo-Json

Output

{
    "users": [{
            "firstName": "name1",
            "lastName": "lastname1",
            "Roles": "empty"
        },
        {
            "firstName": "name2",
            "lastName": "lastname2",
            "Roles": "empty"
        }
    ]
}

But we are leaning towards you are looking for something like this instead...

$json | Add-Member -MemberType NoteProperty -Name roles -Value @('role1','role2')

Output

{
  "users": [
    {
      "firstName": "name1",
      "lastName": "lastname1"
    },
    {
      "firstName": "name2",
      "lastName": "lastname2"
    }
  ],
  "roles": [
    "role1",
    "role2"
  ]
}
  • Related