Read one Value of a specific object from a json file - json

I want to return only the hash value of one object from my test.json file.
Right now, I am getting all hash values with my code.
json file:
[
{
"name": "abc.txt",
"hash": "D23FC7C4C9F1ED7CD147D7D29E3A541D"
},
{
"name": "def.txt",
"hash": "681B75B81734F7215C2DAD1F7EDFDAF7"
},
{
"name": "ghi.txt",
"hash": "81709CDC04EBDBDAA9BA15F6CAF1F05B"
},
{
"name": "xyz.txt",
"hash": "56F07815D06966FA3A73275797496881"
}
]
My code:
$jsonFile = $PSScriptRoot + "\test.json"
(Get-Content $jsonFile | ConvertFrom-Json | where {$_.name -eq 'abc.txt'}).hash

Careful with the parentheses:
((Get-Content $jsonFile | ConvertFrom-Json) | where {$_.name -eq "abc.txt"}).hash
#D23FC7C4C9F1ED7CD147D7D29E3A541D

Like this your json file contains a list of dictionaries. First you need to select which item of your list you want to have and then you can retrieve the value based on the key.
Try something like this:
$jsonFile = $PSScriptRoot + "\test.json"
$jsonList = Get-Content $jsonFile | ConvertFrom-Json
$jsonList[0].hash
Alternatively:
$jsonObject = $jsonList | Where-Object {$_.name -eq 'abc.txt'} | Select-Object hash

Related

(Powershell) Read and change JSON value to a date

I'm trying to write a powershell script that could read a JSON, its extension is .pros, then change the project name from "test" to "test 12/12 13:24" or something similar. So far I was able to read it, but then I can't get to the project_name field.
my code:
$pros = Get-ChildItem -Path $house -Recurse -Include *.pros
$time = Get-Date -Format 'u'
$pog = Get-Content $pros -raw | ConvertFrom-Json
$pog.update | $_.project_name=$time
$pog | ConvertTo-Json -depth 32| set-content $pros
Write-Output $time
The .pros:
{
"py/object": "pros.conductor.project.Project",
"py/state": {
"project_name": "Marcos_Yuck_new",
"target": "v5",
"templates": {
"kernel": {
"location": "/home/dragon/.config/pros/templates/kernel#3.5.3",
"metadata": {

Unable to fetch the json value by using powershell

This is my file structure, I would Like to access Subscription base on the value of "Name"
{
"Topics":
[
{
"Name": "topic1",
"Subscription": "sub1"
},
{
"Name": "topic2",
"Subscription": "sub2"
}
]
}
$json = Get-Content 'path' | Out-String | ConvertFrom-Json
$subscriptions=$json.Topics.Subscription|Where Name -EQ "topic1"
I'm getting the Name by executing following command
$json.Topics.Name
topic1
topic2
$json.Topics.Subscriptions
sub1
sub2
But not sure how to keep this in where clause
Try the following:
$json = #'
{
"Topics":
[
{
"Name": "topic1",
"Subscription": "sub1"
},
{
"Name": "topic2",
"Subscription": "sub2"
}
]
}
'#
$objectFromJson = $json | ConvertFrom-Json
$objectFromJson.Topics | Where-Object Name -eq 'topic1'
The above yields:
Name Subscription
---- ------------
topic1 sub1
If you would like to output only the .Subscription property value, simply use
($objectFromJson.Topics | Where-Object Name -eq 'topic1').Subscription
As for what you tried:
$json.Topics.Subscription
This extracts the values of the Subscription properties, which are mere strings ("sub1" and "sub2"), which don't have a .Name property, so your Where Name -EQ "topic1" filter matches nothing.

Unable to copy json block

I'm trying to copy condition block from id 106 to id 107 with script below; however, I got error "ConvertFrom-Json : Invalid JSON primitive:". Am I missing something? Please advise.
$a = Get-Content 'C:\DevOps\mytest.json' -raw | ConvertFrom-Json
$condition = $a | select -expand environments | select -expand conditions
Write-Host $condition[0]
$a | add-member -Name $condition[1].name -value (Convertfrom-Json $condition[0]) -MemberType NoteProperty
Write-Host $update
$a | ConvertTo-Json -Depth 20 | set content 'C:\DevOps\updatedmytest.json'
The JSON file contains:
{
"source": "userInterface",
"id": 25,
"revision": 3,
"environments": [
{
"id": 106,
"conditions": [
{
"name": "ReleaseStarted",
"conditionType": "event",
"value": ""
}
]
},
{
"id": 107,
"conditions": [
]
}
]
}
Best Regards,
Andy Pham
The error message you are receiving is because you convert the JSON into a PowerShell Object and then saved it into the variable $a. $condition then is still a PowerShell object that you have expanded and is not JSON. So -value (Convertfrom-Json $condition[0]) doesn't work because it's already converted.
Convert to an object, make changes directly to the object, convert from the object.
$ConvertedJSON = Get-Content 'C:\DevOps\mytest.json' -Raw | ConvertFrom-Json
$ConvertedJSON.environments[1].conditions = $ConvertedJSON.environments[0].conditions
$ConvertedJSON | ConvertTo-Json -Depth 20 | Set-Content 'C:\DevOps\updatedmytest.json'
Alternatively, you could use Where-Object to filter for the ids.
$ConvertedJSON = Get-Content 'C:\DevOps\mytest.json' -Raw | ConvertFrom-Json
($ConvertedJSON.environments | Where-Object {$_.id -eq 107}).conditions = ($ConvertedJSON.environments | Where-Object {$_.id -eq 106}).conditions
$ConvertedJSON | ConvertTo-Json -Depth 20 | Set-Content 'C:\DevOps\updatedmytest.json'

How can I craft a csv from multi level json in powershell?

I am trying to parse a JSON response that looks like
{
"Objects": [
{
"Name": "FirstName",
"Type": "XXXX",
},
{
"Name": "SecondName",
"Type": "YYYY",
},
{
"Name": "ThirdName",
"Type": "ZZZZ",
},
],
"TotalCount": 127
}
I want a CSV formatted like
"Name","Type"
"FirstName","XXXX"
"SecondName","YYYY"
and so on.
I tried creating a PSCustomObject and using Select-Object with it to generate the CSV but it does not give me the desired output.
My code:
$report=$null
foreach($obj in $json){
$item=$obj | ConvertFrom-Json
$report=[pscustomobject]#{
Name=($item.Objects.Name | Out-String).Trim()
Type=($item.Objects.Type | Out-String).Trim()
}
$report | Select-Object Name,Type | Export-Csv "PATH"`
Gives me CSV that looks like:
"Name","Type"
"FirstName
SecondName
ThirdName",
"XXXX
YYYY
ZZZZ"
if you really want the total count in the csv as well, here is one thing you could do:
$psobjarray = ($json | convertfrom-json)
$psobjarray.objects | Select-Object Name,Type | Export-Csv $Path
"Total Count: $($psobjarray.totalcount)" | out-file $Path -append

How do I update JSON file using PowerShell

I have one json file mytest.json like below I want to update values using PowerShell script
update.json
{
"update": [
{
"Name": "test1",
"Version": "2.1"
},
{
"Name": "test2",
"Version": "2.1"
}
]
}
I want to write a PowerShell script where if Name=="test1" I want to update Version= "3"
How can i do it using parameters?
Here is a way :
$a = Get-Content 'D:\temp\mytest.json' -raw | ConvertFrom-Json
$a.update | % {if($_.name -eq 'test1'){$_.version=3.0}}
$a | ConvertTo-Json -depth 32| set-content 'D:\temp\mytestBis.json'
According to #FLGMwt and #mikemaccana I improve the ConvertTo-Json with -depth 32 because the default depth value is 2 and for object deeper than 2 you will receive class informations in spite of objects.
I have also faced the same kind of issue. I was looking to change the records of the below JSON file
{
"SQS_QUEUE_URL": "https://que-url.com/server1",
"SQS_EVENTS_QUEUE_URL": "https://events-server.com/server1/development_events",
"REGION": "region1",
"BUCKET": "test-bucket",
"AE_WORK_PATH": "C:\\workpath\\path1",
"ENV": "env"
}
Finally, I managed to find the easiest way to generate a JSON file from Powershell.
$json = Get-Content "c:\users\bharat.gadade\desktop\test.json" | ConvertFrom-Json
$json.SQS_QUEUE_URL = "https://que-url.com/server2"
$json.SQS_EVENTS_QUEUE_URL = "https://events-server.com/Server2/development_events"
$json.REGION = "region1 "
$json.BUCKET = "test-bucket"
$json.AE_WORK_PATH = "C:\workpath\path1"
$json.ENV = "env"
$json | ConvertTo-Json | Out-File "c:\users\bharat.gadade\desktop\test.json"