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": "************"
}
Related
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 no experience with PowerShell and I was asked to create this script as a favor for a friend of mine. The script is supposed to read a csv file (These files have different columns except for time and host, which are common among all files), and output its content into a JSON file of the following format:
CSV file contains columns:
host| message | time | severity | source |
{
"time": 1437522387,
"host": "dataserver992.example.com",
"event": {
"message": "Something happened",
"severity": "INFO",
"source": "testapp"
#...All columns except for time and host should be under "event"
}
}
*The only guaranteed columns are time and host. All other column headers vary from file to file.
This is part of what I have so far:
$csvFile = Import-Csv $filePath
function jsonConverter($file)
{
#Currently not in use
$eventString = $file| select * -ExcludeProperty time, host
$file | Foreach-Object {
Write-Host '{'
Write-Host '"host":"'$_.host'",'
Write-Host '"time":"'$_.time'",'
Write-Host '"event":{'
#TODO: Put all other columns (key, values) under event - Except for
time and host
Write-Host '}'
}
}
jsonConverter($csvFile)
Any ideas of how I could extract only the remaining columns, row by row, outputting its content to a key, value JSON format like the example above?
Thank you!
Provided your csv looks like this:
"host","message","time","severity","source"
"dataserver992.example.com","Something happened","1437522387","INFO","testapp"
this script:
$filepath = '.\input.csv'
$csvData = Import-Csv $filePath
$NewCsvData = foreach($Row in $csvData){
[PSCustomObject]#{
time = $Row.time
host = $Row.host
event = ($Row| Select-Object -Property * -ExcludeProperty time,host)
}
}
$NewCsvData | ConvertTo-Json
will output this Json:
{
"time": "1437522387",
"host": "dataserver992.example.com",
"event": {
"message": "Something happened",
"severity": "INFO",
"source": "testapp"
}
}
If your powershell version is 3.0 or higher (it should):
Import-CSV $filepath | ConvertTo-JSON
Done!
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
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
The following JSON is getting returned from OData API service:
{
"d": {
"results": [
{
"FileSystemObjectType": 0,
"Id": 1,
"ContentTypeId": "0x0100BC97B2F575CB0C42B79549F3BABD32A8",
"Title": "Nokia California",
"Address": "200 South Matilda Avenue\nW Washington Ave\n94086 Sunnyvale, California\nUnited States of America",
"ID": 1,
"Modified": "2014-02-24T10:06:39Z",
"Created": "2014-02-24T10:06:39Z",
"AuthorId": 12,
"EditorId": 12,
"OData__UIVersionString": "1.0",
"Attachments": false,
"GUID": "d12aafad-502a-4968-a69e-36a7ea05ec80"
}
]
}
}
and saved as a string into variable named $data
An attempt to convert a JSON-formatted string to a custom object using ConvertFrom-Json cmdlet:
$results = $data | ConvertFrom-Json
gives the following error:
ConvertFrom-Json : Cannot convert the JSON string because a dictionary
that was converted from the string contains the duplicated keys 'Id'
and 'ID'.
Is there any way to convert the specified JSON-formatted string in PowerShell?
This is how I have done with it:
$results = $data.ToString().Replace("ID", "_ID") | ConvertFrom-Json
Note, both examples assume the JSON is stored in the $jsonstring variable.
In PowerShell Core, ConvertFrom-Json -AsHashtable is the easiest alternative:
$json = $jsonstring | ConvertFrom-Json -AsHashtable
$json['d']['results']
Name Value
---- -----
Modified 2/24/2014 10:06:39 AM
Title Nokia California
Attachments False
ID 1
ContentTypeId 0x0100BC97B2F575CB0C42B79549F3BABD32A8
GUID d12aafad-502a-4968-a69e-36a7ea05ec80
Created 2/24/2014 10:06:39 AM
EditorId 12
AuthorId 12
Address 200 South Matilda Avenue…
Id 1
OData__UIVersionString 1.0
FileSystemObjectType 0
In Windows PowerShell, you can use the Deserialize(String, Type) method from the JavaScriptSerializer Class.
Add-Type -AssemblyName System.Web.Extensions
$serializer = [Web.Script.Serialization.JavaScriptSerializer]::new()
$json = $serializer.Deserialize($jsonstring, [hashtable])
$json['d']['results']
In PowerShell V1.0, or in PowerShell V2.0 when the JSON is too big, I still use a convertion to XML :
Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
function Convert-JsonToXml
{
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN
{
$mStream = New-Object System.IO.MemoryStream
}
PROCESS
{
$json | Write-String -stream $mStream
}
END
{
$mStream.Position = 0
try
{
$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
$xml = New-Object Xml.XmlDocument
$xml.Load($jsonReader)
$xml
}
finally
{
$jsonReader.Close()
$mStream.Dispose()
}
}
}
Using this code you can loop thru your items you can test :
$a = Get-Content C:\temp\jsontest.txt
$b.root.d.results.Item
$b.root.d.results.Item[7].Id[0].InnerText
(Edited)
In you case I would only replace the expected duplicate ID/Id
$data = Get-Content C:\temp\jsontest.txt -Raw
$datacorrected = $a -creplace '"Id":','"Id-minus":'
$psJsonIn = $datacorrected | ConvertFrom-Json
If really you've got unexpected duplicate you can write a function that trap the convertion error due to duplicated key and replace one.
ConvertFrom-JSON it going to try to create a PS Custom Object from the JSON string. PowerShell object property names are case-insensitive, so "ID" and "id" represent the same property name. You're going to have to do something with those duplicate property names in your JSON before you try to do that conversion, or it's going to fail.
I used the ToLower() before converting the json to object, resolved my issue.
$sdf = $data.ToLower() | ConvertFrom-Json