I want to Read Multiple values from Json file
My Json file Looks like this
{
"TestEvent": ["TVIA_Gold","TVIA_Silver"],
"Folder": ["DealerPortal","VehiclePortal"],
"NEL": [3,1]
}
Output should be like:
TVIA_Gold
DealerPortal
3
TVIA_Silver
VehiclePortal
1
Or
TestEvent Folder NEl
TVIA_GOLD DealerPortal 3
TVIA_SILVER VehiclePortal 1
My code is below:
$file= Get-Content "C:\Test.json"
$file2=$file
$file=$file2 | ConvertFrom-Json
$vPSObject= $file2 | ConvertFrom-Json
$vPSObject.TestEvent
$vPSObject.Folder
$vPSObject.NEL
Output :
TVIA_Gold
TVIA_Silver
DealerPortal
VehiclePortal
3
1
...but it doesn't work. Should I use array and loop with it?
Your JSON data seems invalid for output you expect. Instead it should be something like this then:
[
{
"TestEvent": "TVIA_GOLD",
"Folder": "DealerPortal",
"NEl": "3"
},
{
"TestEvent": "TVIA_SILVER",
"Folder": "VehiclePortal",
"NEl": "1"
}
]
If you insist to use your JSON input data as shown by you you may assume there is a relation between the elements of the actually unrelated single arrays in your JSON data. Then you could use something like this:
$ImportData = Get-Content -Path C:\test.json | ConvertFrom-Json
for ($i = 0; $i -lt $ImportData.testevent.Count; $i++) {
[PSCustomObject]#{
TestEvent = $ImportData.TestEvent[$i]
Folder = $ImportData.Folder[$i]
NEL = $ImportData.NEL[$i]
}
}
Related
One requirement of mine is - Using windows, not use any tools not already available as part of aws cli or windows
For example, I have this json file test.json with below content:
"My number is $myvar"
I read this into a powershell variable like so:
$myobj=(get-content .\test.json | convertfrom-json)
$myvar=1
From here, I would like to do something with this $myobj which will enable me to get this output:
$myobj | tee json_with_values_from_environment.json
My number is 1
I got some limited success with iex, but not sure if it can be made to work for this example
You can use $ExecutionContext.InvokeCommand.ExpandString()
$myobj = '{test: "My number is $myvar"}' | ConvertFrom-Json
$myvar = 1
$ExecutionContext.InvokeCommand.ExpandString($myobj.test)
Output
My number is 1
Here is one way to do it using the Parser to find all VariableExpressionAst and replace them with the values in your session.
Given the following test.json:
{
"test1": "My number is $myvar",
"test2": {
"somevalue": "$env:myothervar",
"someothervalue": "$anothervar !!"
}
}
We want to find and replace $myvar, $myothervar and $anothervar with their corresponding values defined in the current session, so the code looks like this (note that we do the replacement before converting the Json string into an object, this way is much easier):
using namespace System.Management.Automation.Language
$isCore7 = $PSVersionTable.PSVersion -ge '7.2'
# Define the variables here
$myvar = 10
$env:myothervar = 'hello'
$anothervar = 'world'
# Read the Json
$json = Get-Content .\test.json -Raw
# Now parse it
$ast = [Parser]::ParseInput($json, [ref] $null, [ref] $null)
# Find all variables in it, and enumerate them
$ast.FindAll({ $args[0] -is [VariableExpressionAst] }, $true) |
Sort-Object { $_.Extent.Text } -Unique | ForEach-Object {
# now replace the text with the actual value
if($isCore7) {
# in PowerShell Core is very easy
$json = $json.Replace($_.Extent.Text, $_.SafeGetValue($true))
return
}
# in Windows PowerShell not so much
$varText = $_.Extent.Text
$varPath = $_.VariablePath
# find the value of the var (here we use the path)
$value = $ExecutionContext.SessionState.PSVariable.GetValue($varPath.UserPath)
if($varPath.IsDriveQualified) {
$value = $ExecutionContext.SessionState.InvokeProvider.Item.Get($varPath.UserPath).Value
}
# now replace the text with the actual value
$json = $json.Replace($varText, $value)
}
# now we can safely convert the string to an object
$json | ConvertFrom-Json
If we were to convert it back to Json to see the result:
{
"test1": "My number is 10",
"test2": {
"somevalue": "hello",
"someothervalue": "world !!"
}
}
As I am new to Powershell, can someone please support on the looping part?
Below is the json format from Test.json file:
{
"Pre-Production_AFM": {
"allowedapps": ["app1", "app2"]
},
"Production_AFM": {
"allowedapps": ["app1", "app2"]
}
}
I am reading the json file as below
$json = (Get-Content "Test.json" -Raw) | ConvertFrom-Json
I need to loop and get the 1st and 2nd objects - "Pre-Production_AFM" and "Production_AFM" one after another dynamically.
right now I have written the code as below :
foreach($i in $json){
if($i -contains "AFM"){
Write host "execute some code"
}
}
My dout is - Will $i holds the object "Pre-Production_AFM" dynamically?
If not please suggest the way to get the objects one after one dynamically for further execution.
# read the json text
$json = #"
{
"Pre-Production_AFM": {
"allowedapps": ["app1", "app2"]
},
"Production_AFM": {
"allowedapps": ["app1", "app2"]
}
}
"#
# convert to a PSCustomObject
$data = $json | ConvertFrom-Json
# just to prove it's a PSCustomObject...
$data.GetType().FullName
# System.Management.Automation.PSCustomObject
# now we can filter the properties by name like this:
$afmProperties = $data.psobject.Properties | where-object { $_.Name -like "*_AFM" };
# and loop through all the "*_AFM" properties
foreach( $afmProperty in $afmProperties )
{
$allowedApps = $afmProperty.Value.allowedApps
# do stuff
}
I'm trying to access a JSON attribute which contains an array of strings, using PowerShell
JSON
{
"id": "00000000-0000-0000-0000-000000000000",
"teamName": "Team A",
"securityGroups": [{
"name": "Security Group 1",
"members:": ["abc#mail.com", "def#mail.com", "ghi#mail.com"]
},
{
"name": "Securiy Group 2",
"members:": ["123#mail.com", "456#mail.com", "789#mail.com"]
}]
}
PowerShell
$json = Get-Content 'test.json' | ConvertFrom-Json
ForEach($group in $json.securityGroups)
{
Write-Host "Team: $($group.name)"
ForEach($member in $group.members)
{
Write-Host "Member: $($member)"
}
}
Output
Team: Security Group 1
Team: Securiy Group 2
As you can see, only the name of the security group (securityGroup.name) gets shown. I'm unable to access the securityGroups.members node, which contains an array of strings (containing emails). My goal is to store this list of strings and loop through them.
When I check to see how the $json object looks like in PS, I get the following:
PS C:\Users\XYZ> $json
id teamName securityGroups
-- -------- --------------
00000000-0000-0000-0000-000000000000 Team A {#{name=Security Group 1; members:=System.Object[]}, #{name=Securiy Group 2; members:=System.Object[]}}
What am I missing here?
You can use this:
$json = Get-Content 'test.json' | ConvertFrom-Json
ForEach ($group in $json.securityGroups)
{
Write-Host "Team: $($group.name)"
ForEach ($member in $group."members:")
{
Write-Host "Member: $($member)"
}
}
You haven't noted that member key contains a colon at the end. Otherwise it will give you wrong result.
I have imported some JSON data and converted it to a PowerShell Object. I would like to understand how to retrieve specific portions of said data.
test.json:
{
"Table": {
"Users": {
"Columns": [ "[Id]",
"[FName]",
"[MName]",
"[SName]",
"[UName]",
"[Pasword]" ],
"data": "CustomUserData"
},
"Roles": {
"Columns": [ "[Id]",
"[Role]",
"[Description]" ],
"data": "CustomRoleData"
}
}
}
Import to PS Object:
$userdata = Get-Content .\test.json |ConvertFrom-Json
Retrieve and format column data:
PS> $userdata = Get-Content ./test.json |ConvertFrom-Json
PS> $columns = $userdata.Table.Users.Columns -join ","
PS> $columns
[Id],[FName],[MName],[SName],[UName],[Pasword]
Example retrieval of custom data:
PS> $userdata.Table.Users.data
CustomUserData
What I would like to do is:
Select just the table names. When I try and do this by calling $userdata.table I get the following:
PS> $userdata.Table |Format-List
Users : #{Columns=System.Object[]; data=CustomUserData}
Roles : #{Columns=System.Object[]; data=CustomRoleData}
What I am looking for is just a list of the table names, in this case - Users,Roles
I would also like to know how to leverage this to create a ForEach loop which cycles through each table name and prints the columns associated with each table - ultimately I will be using this to craft a SQL query.
Thank you!
Maybe this can help you.
It is a small function to output the property names recursively.
function Get-Properties($obj, [int]$level = 0) {
$spacer = " "*$level
$obj.PSObject.Properties | ForEach-Object {
$spacer + $_.Name
if ($_.Value -is [PSCustomObject]){
Get-Properties $_.Value ($level + 2)
}
}
}
In your case, you can use it like this:
$userdata = Get-Content ./test.json | ConvertFrom-Json
Get-Properties $userData
The console output will look like this:
Table
Users
Columns
data
Roles
Columns
data
JSON:
[
{
"Category-1": [
"Value1"
]
},
{
"Category-2": [
"Value1"
]
},
{
"Category-3": [
"Value1",
"Value2"
]
}
]
PowerShell Script:
$jsonToParse = (Get-Content -Path $jsonPath) -join "`n" | ConvertFrom-Json
foreach ($entry in $jsonToParse) {
log -Message ($entry) #Log function spits output to file
}
Output:
[10:39:03]#{Category-1=System.Object[]}
[10:39:03]#{Category-2=System.Object[]}
[10:39:03]#{Category-3-Med=System.Object[]}
How can I parse this? I have square brackets mixed with curly brackets, and I'm having a hard time finding a foothold with which to really get at the data.
What can I do to get the "Category" names? What can I do to get the "Values" for each category name? The fact that these aren't all key/value pairs is what's causing me trouble, I think.
I think what you are after is something like this:
# use the -Raw switch to get the file content as one single string
$jsonToParse = Get-Content -Path $jsonPath -Raw | ConvertFrom-Json
foreach ($entry in $jsonToParse) {
# format a string for the log file using the object ($entry) Name followed by the Value
# This Value can be an array of more than one items, so join these with a comma
$msg = '{0} = {1}' -f $entry.PSObject.Properties.Name, ($entry.PSObject.Properties.Value -join ', ')
log -Message $msg #Log function spits output to file
}
output:
[10:39:03]Category-1 = Value1
[10:39:03]Category-2 = Value1
[10:39:03]Category-3 = Value1, Value2
You have an array which contains values ("Category-1" etc). The values contain arrays with values ("Value1" etc).
$jsonToParse[0] = Category-1
$jsonToParse[1] = Category-2
$jsonToParse[2] = Category-3
$jsonToParse[1].'Category-2' = Value1
If you fill in the above examples, the output is like this!