Json Error: Missing property name after reference operator - json

When I try to access the below JSON file from powershell it show the following error: Missing property name after reference operator. Here is my JSON file:
{
"Vnet": {
"Service": "VirtualNetwork",
"Name": "vnetname",
"ResourceGroupName": "RGname",
"Location": "Southeast Asia",
"Address_Prefix": "11.0.0.0/16",
"No_of_subnets": "1",
"Subnet": {
"1": {
"SubnetName":"sub1",
"Address_Prefix":"11.0.1.0/24"
}
}
}
}
Here is the simple powershell command
$file = (Get-Content "//filelocation" | Out-String) | ConvertFrom-Json
Write-Output $file.Vnet.Subnet.1.SubnetName
Note: I'm author of the JSON file and I can make any changes to it too if needed.

PowerShell seems to misinterpret the 1 as an index. Put it in quotes (to make clear it's a property name) and the code will work as you expect:
Write-Output $file.Vnet.Subnet.'1'.SubnetName

Related

Access JSON array via PowerShell

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.

Inputting JSON data in Powershell

Currently, I'm attempting to call upon an API to run a POST, with JSON data as the body. So I was wondering if anyone would be able to tell me how I need to format the text below inside the variable $postParams. I'm pretty new at working with JSON so I'm having so trouble with this.
Currently, I only have the following and don't know what to do about the second line on.
$postParams = #{name='Example'}
Here's is the entire data I was hoping to add to $postParams. So if you could help me with the 2nd, 4th, and 8th that'd be awesome. Thanks!
{
"name":"Example",
"template":{"name":"Template"},
"url":"http://localhost",
"page":{"name":"Landing Page"},
"smtp":{"name":"Sending Profile"},
"launch_date":"2019-10-08T17:20:00+00:00",
"send_by_date":null,
"groups":[{"name":"test group"}]
}
You'll need a here-string and ConvertFrom-Json.
here-string:
Quotation marks are also used to create a here-string. A here-string is a single-quoted or double-quoted string in which quotation marks are interpreted literally. A here-string can span multiple lines. All the lines in a here-string are interpreted as strings, even though they are not enclosed in quotation marks.
The resulting code:
# Use a PowerShell here string to take JSON as it is
$jsonString = #"
{
"name":"Example",
"template":{"name":"Template"},
"url":"http://localhost",
"page":{"name":"Landing Page"},
"smtp":{"name":"Sending Profile"},
"launch_date":"2019-10-08T17:20:00+00:00",
"send_by_date":null,
"groups":[{"name":"test group"}]
}
"#
# Pipe the string to create a new JSON object
$jsonObject = $jsonString | ConvertFrom-Json
# The resulting JSON object has properties matching the properties in the orig. JSON
$jsonObject.name
$jsonObject.url
# Nested property
$jsonObject.template.name
# Nested property in array
$jsonObject.groups[0].name
I've posted an online version of the above code at tio.run, so you can play around with it.
If you want to update several properties of the $jsonObject you can do the following:
$jsonObject.name = "NEW NAME"
$jsonObject.url = "NEW URL"
$jsonObject | ConvertTo-Json
ConvertTo-Json will take your object and create an appropriate JSON string:
{
"name": "NEW NAME",
"template": {
"name": "Template"
},
"url": "NEW URL",
"page": {
"name": "Landing Page"
},
"smtp": {
"name": "Sending Profile"
},
"launch_date": "2019-10-08T17:20:00+00:00",
"send_by_date": null,
"groups": [
{
"name": "test group"
}
]
}
If you $jsonObject has more than two levels of depth, use the -Depth parameter, otherwise not all object information will be included in the JSON string.
ConvertTo-Json:
-Depth
Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.
Here is a tio.run link to a ConvertTo-Json example.
Hope that helps.
I can't test it currently, but try this.
$postParams = #'
{
"name":"Example",
"template":{"name":"Template"},
"url":"http://localhost",
"page":{"name":"Landing Page"},
"smtp":{"name":"Sending Profile"},
"launch_date":"2019-10-08T17:20:00+00:00",
"send_by_date":null,
"groups":[{"name":"test group"}]
}
'#
Make a hashtable, then convert to JSON:
$Hashtable = #{
Key1 = "Value1"
Key2 = "Value2"
}
$Json = $Hashtable | ConvertTo-Json

Recover objects from JSON file using PowerShell

I have a creds.json file that has the following structure
{
"username": "Administrator"
"password": "************"
}
I want to retrieve both "Administrator" and "***********" value using powershell script that I wrote :
$creds= (Get-Content C:\Users\lamda\Desktop\creds.json | Out-
String | ConvertFrom-Json)
$admin = $creds.username
$password = $creds.password
Write-Host $admin
but the following error shows up
`ConvertFrom-Json : Invalid object passed in, ':' or '}'
Your JSON file is missing a comma as a separator. It should be formatted as such:
{
"username": "Administrator",
"password": "************"
}

Reading JSON from Powershell

I am trying to read JSON data which is stored in VM notes. Below is the command i execute to get the VM notes
Get-VM testbox |format-list Notes
The output is
Notes : {
"Program": "AAA",
"Project": "BBBB"
}
I want to read the value of Program into a variable. How can i do it ?
Use ConvertFrom-JSON to parse the JSON-value in your notes-property. I'd store the converted notes in a variable just in case you need to access Project or another part of the json later. Try:
$vm = Get-VM testbox
$notes = $vm.Notes | ConvertFrom-JSON
$mynewvar = $notes.program
Your json is not valid, if it was this would work:
(Get-VM -VMName TestBox).notes | ConvertFrom-Json
Valid Json:
{
"Notes":
{
"Program": "AAA",
"Project": "BBBB"
}
}
Totally untested (and can't test right now) but something like:
Get-VM testbox | Select-Object -ExpandProperty Notes | ConvertFrom-Json
Documentation for ConvertFrom-Json here

Iterate through json custom object

I'm trying to perform some config transformations on JSON files using PowerShell.
For this there's several input json files and a transform one (one for each environment).
Input sample (AzureStorage.json):
{
"$schema": "http://datafactories.schema.management.azure.com/schemas/2015-09-01/Microsoft.DataFactory.LinkedService.json",
"name": "AzureStorage",
"properties": {
"type": "AzureStorage",
"typeProperties": {
"connectionString": "My Connection String here"
} } }
Transform:
{
"$schema": "http://datafactories.schema.management.azure.com/vsschemas/V1/Microsoft.DataFactory.Config.json",
"AzureStorage": [
{
"name": "$.properties.typeProperties.connectionString",
"value": "DefaultEndpointsProtocol=https;AccountName=mytestaccount;AccountKey=d;lasfjdalfdjfldjfdsfds;EndpointSuffix=core.windows.net"
}
],
"DataLakeStore": [
{
"name": "$.properties.typeProperties.dataLakeStoreUri",
"value": "https://mydatalake.azuredatalakestore.net/webhdfs/v1"
}
]
}
What I need to do, is to load the transform file, then traverse it, finding the names of the input files I need to transform (in this example AzureStorage.json and DataLakeStore.json).
Next, I need to replace the properties accordingly. I'm trying to do it by loading the transform file into a variable using ConvertFrom-Json, but I not sure how to traverse it afterwards.
I don't know hat exactly you need. I'm guessing access to the information within the JSON file.
What about this approach?
$json_object = Get-Content -Raw -Path '<your_path>\transform.json' | ConvertFrom-Json
$azure_storage = #('AzureStorage'; 'DataLakeStore')
ForEach ($azure in $json_object) {
ForEach ($storage in $azure_storage) {
Write-Output $azure.$storage.name
Write-Output $azure.$storage.value
}
}
Edit Due to edit I got it. You need a generic access.
Here you go:
$json_object = (Get-Content -Path '<your_path>\transform.json') -join "`n" | ConvertFrom-Json
ForEach ($object in $json_object.PsObject.Properties) {
Write-Output $object.name
Write-Output $object.value
}
Explanation:
(Get-Content -Path '<your_path>\transform.json') -join "n"` is a Microsoft's MSDN recommended way to read json files.
You need to find out where the values are. The object you are using is a "Windows PowerShell custom object" - PsObject. To access the you need to use .Properties.value. Then you have the Strings you want and you can access them using .name and .value.