Retrieve value from Json object with field having dots and hyphen in powershell - powershell

I want to retrieve value of a field present in json object. The filed name has dots and hyphen.
For eg:
$json = #"
{
"Stuffs":
{
"Name.new-name": "Darts",
"Type": "Fun Stuff"
}
}
"#
How can I get the value Darts?
I tried some approaches like
$x = $json | ConvertFrom-Json
$x.Stuffs.(Name.new-name)
But it doesn't work.

Try this
$x.Stuffs.'Name.new-name'

Related

Issue with API result not converting to object in powershell

I have an odd problem. I'm getting some data back from an API and storing it in $response
The result looks like this (I've changed the names and IDs):
accountId : 1234
secureScoreProgress : #{startDate=2022-12-12 00:00:00.000; endDate=2023-01-26 00:00:00.000; totalDays=2738; minScore=76; maxScore=534.18; averageScore=257.33; data=System.Object[]}
monitoredAccounts : #{total=479; data=System.Object[]}
accountIdToNameMap : #{1234=Apple; 5432=Microsoft; 2584=Tesla; 7533=Ben and Jerry; 7534=Micool Paul Inc; 7549=AGLX; 7558=Samsung}
I'm interested in the 'accountIdToNameMap' section, so I store it to an object like so:
$accounts = $response.accountIdToNameMap
This returns the following list:
1234 : Apple
5432 : Microsoft
2584 : Tesla
7533 : Ben and Jerry
7534 : Micool Paul Inc
7549 : AGLX
7558 : Samsung
If I try to do a foreach on the list, it only loops once and outputs that whole list in one go.
I've tried to ConvertFrom-JSON but that throws Invalid JSON primitive: .
I've tried to ConvertTo-JSON, which works, but I still can't loop through the results. After ConvertTo-JSON, the result looks like this:
{
"1234": "Apple",
"5432": "Microsoft",
"2584": "CH Hausmann",
"7533": "Hughes Fowler Carruthers",
"7534": "Tempest Resourcing",
"7549": "Cream UK Ltd",
"7558": "Illuminatis / Scout Data"
}
What am I doing wrong?
If I try to do a foreach on the list
It's not a list, it's an object. You can enumerate its properties by accessing the hidden psobject member:
foreach ($property in $accounts.psobject.Properties) {
"The `$accounts object has a property named '$($property.Name)' with value '$($property.Value)'"
}
You can use this to build a hashtable (an unordered dictionary):
$idToNameMap = #{}
foreach ($property in $accounts.psobject.Properties) {
$idToNameMap[$property.Name] = $property.Value
}
Now you can easily use it as a lookup table:
$idToNameMap['1234'] # resolves to "Apple"

A dictionary inside of a dictionary in PowerShell

So, I'm rather new to PowerShell and just can't figure out how to use the arrays/lists/hashtables. I basically want to do the following portrayed by Python:
entries = {
'one' : {
'id': '1',
'text': 'ok'
},
'two' : {
'id': '2',
'text': 'no'
}
}
for entry in entries:
print(entries[entry]['id'])
Output:
1
2
But how does this work in PowerShell? I've tried the following:
$entries = #{
one = #{
id = "1";
text = "ok"
};
two = #{
id = "2";
text = "no"
}
}
And now I can't figure out how to access the information.
foreach ($entry in $entries) {
Write-Host $entries[$entry]['id']
}
=> Error
PowerShell prevents implicit iteration over dictionaries to avoid accidental "unrolling".
You can work around this and loop through the contained key-value pairs by calling GetEnumerator() explicitly:
foreach($kvp in $entries.GetEnumerator()){
Write-Host $kvp.Value['id']
}
For something closer to the python example, you can also extract the key values and iterate over those:
foreach($key in $entries.get_Keys()){
Write-Host $entries[$key]['id']
}
Note: You'll find that iterating over $entries.Keys works too, but I strongly recommend never using that, because PowerShell resolves dictionary keys via property access, so you'll get unexpected behavior if the dictionary contains an entry with the key "Keys":
$entries = #{
Keys = 'a','b'
a = 'discoverable'
b = 'also discoverable'
c = 'you will never find me'
}
foreach($key in $entries.Keys){ # suddenly resolves to just `'a', 'b'`
Write-Host $entries[$key]
}
You'll see only the output:
discoverable
also discoverable
Not the Keys or c entries
To complement Mathias R. Jessen's helpful answer with a more concise alternative that takes advantage of member-access enumeration:
# Implicitly loops over all entry values and from each
# gets the 'Id' entry value from the nested hashtable.
$entries.Values.Id # -> 2, 1
Note: As with .Keys vs. .get_Keys(), you may choose to routinely use .get_Values() instead of .Values to avoid problems with keys literally named Values.

powershell convert-tojson not giving optimal results

I have a powershell question, I need to convert this piece of code to Json
$Dimensions = #(
#{
name = 'num_vm'
value = '100'
},
#{
name = 'days'
value = '10'
},
#{
name = 'months'
value = '12'
}
)
For ($i=0;$i -lt $Dimensions.length;$i++)
{
$bodymessage = #{'resourceId' = $resourceUsageId; 'quantity' = "$Dimensions[$i].value"; 'dimension' = "$Dimensions[$i].name"; 'effectiveStartTime' = $lastHourMinusFiveMinutes; 'planId' = 'plan_meter' }
$body += #{
request =
#($bodymessage)} `
|ConvertTo-Json -Depth 5
}
$body
what I'm hoping, is it can dynamically create the JSON output according to the dimension input,
but the result I got is this
{
"request": [
{
"resourceId": null,
"quantity": "System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable[0].value",
"planId": "plan_meter",
"dimension": "System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable[0].name",
"effectiveStartTime": null
}
]
}{
"request": [
{
"resourceId": null,
"quantity": "System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable[1].value",
"planId": "plan_meter",
"dimension": "System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable[1].name",
"effectiveStartTime": null
}
]
}{
"request": [
{
"resourceId": null,
"quantity": "System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable[2].value",
"planId": "plan_meter",
"dimension": "System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable[2].name",
"effectiveStartTime": null
}
]
}
how can i get rid of System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable[0].value?
and displaying with real value?
The main issue is how you're assigning the hashtable element values within a string. Fix it by removing the quotes like so (formatted multiline for readability):
$bodymessage = #{
resourceId = $resourceUsageId;
quantity = $Dimensions[$i].value; # Removed the quotes here
dimension = $Dimensions[$i].name; # Removed the quotes here
effectiveStartTime = $lastHourMinusFiveMinutes;
planId = 'plan_meter';
}
Note: I've also removed the single-quotes ' around the key names since they are not needed in this context. You only need to quote key names if non-alphanumeric characters are part of the key name, and you are assigning the key name as a literal string.
Why did this happen?
This happens because of how variable expansion within strings works. The following string you originally had:
"$Dimensions[$i].value"
will see $Dimensions get expanded (its ToString() function is implicitly called), not $Dimensions[$i].value. This is because variable parsing starts at the dollar-sign $ and stops at the first character which can't normally be part of a variable name. This will be most special characters, excepting the colon :.
However, if you are trying to force a string value (and you may not be), you can perform a sub-expression within the string to evaluate the members of an object, including array-accessors and object properties. You can also perform more complex expressions as well, but for your case below you could leave the quotes and use $() to get the result you want:
"$($Dimensions[$i].value)"
The $() tells the parser to "run this expression and put the result into the string". Again, whatever object is returned will implicitly have ToString() run on it when it gets inserted into the final string, so whatever output $Dimensions[$i].value.ToString() produces will be your string value.

ConverTo-Json altering intended output

I have a psobject that is created from the JSON output of an Invoke-RestMethod. My intention is to change one value, convert back to JSON, then add back to the application REST API with another Invoke-RestMethod. I have done this several times in the past with the same REST API so I'm not sure why this one isn't working.
The psobject $restOut looks like this:
id: 123
limit: #{limitMb=0; limitPercent=0}
The next block of code changes the id if the new id I want isn't already set
$newId = 456
if($restOut.id -ne $newId){
$restOut.id = $newId
$inputJson = $restOut | ConvertTo-Json -Depth 2
Invoke-RestMethod -Uri $restURl -Method PUT -Body $inputJson
}
I'm expecting $inputJson to look like this (and the psobject $restOut does match the expectation):
{
"id": "456",
"limit": {
"limitMb": 0,
"limitPercent": 0
}
}
But what I'm actually getting is:
{
"id": {
"value": "456",
"id": "456"
},
"limit": {
"limitMb": 0,
"limitPercent": 0
}
}
As said, I've done this exact manipulation many times in other scripts targeting the same software API, and am just at a loss with the behavior this time. Any help is appreciated. Thanks!
Easy fix
This was a simplified sample. In my actual script $newId = 456 was actually being assigned from another API call. Therefore it was also an object. Simply quoting it in the line that changes the id to make it a string fixed the issue:
$restOut.id = "$newId"
instead of
$restOut.id = $newId

PowerShell PSObject change field names before converted to JSON object

I have a project in PowerShell where I created a custom type using the "Add-Type". I wanted to use classes, but I'm limited to the PowerShell version on the system I have to use.
This object gets converted to JSON and is sent out using a REST API. To avoid some naming issues I ended up pre-pending ""s to the field names. I want to remove those before it is sent to the API. I thought it would be simple to do the rename, and it was, but then I realized the method I used for the rename would potentially cause issues if I renamed everything in the JSON object by removing anything with the "".
Here is the custom type:
Add-Type -typedef #"
public class SearchFilter
{
public int _filterOrder;
public string _property;
public string _direction;
public string _value;
public string[] _values;
public string _operator;
public SearchFilter()
{
_filterOrder = 0;
_property = "";
_direction = "";
_value = "";
_values = new string[0];
_operator = "";
}
}
"#
Using just a string REPLACE method I'll get this:
{
"filterOrder": 0,
"property": "name",
"direction": "ASC",
"value": "value",
"values": [],
"operator": "Contains"
}
instead of this:
{
"filterOrder": 0,
"property": "name",
"direction": "ASC",
"value": "_value_",
"values": [],
"operator": "Contains"
}
Here is the method I'm using:
# Create search filter object
$searchFilter = New-Object -TypeName "SearchFilter"
# Convert search filter to REST API JSON format
$apiPostBody = ConvertTo-Json -InputObject $searchFilter
# Remove all "_"
$apiPostBody = $apiPostBody .Replace("_","")
I have checked the methods available from PSObject, but I'm just not sure of the syntax. If possible I'd like to change the existing object before converting to JSON as opposed to having to create a CLONE or iterate through the JSON value.