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"
Related
I am importing JSON into Powershell to replace some values, but I also need to remove some objects from there.
Import:
$fileJson = Get-Content -path/Template.json -Encoding UTF8
I have an array of object which looks like this:
{
"resources": [
{
"name": "name1"
"type": "type1"
"....": "....."
},
{
"name": "name2"
"type": "type2"
"....": "....."
},
{
"name": "name3"
"type": "type1"
"....": "....."
}
]
}
and I want to remove a specific object from this array of objects. For example I want to remove Object where "type" equals "type2".
I have already tried to replace values with .Replace, however I can only replace single values and not the complete object.
Is it possible to delete or skip entire object with condition?
Convert the JSON to a custom object:
$fileJson = Get-Content -path/Template.json -Encoding UTF8
$data = $fileJson |ConvertFrom-Json
Use Where-Object to filter the resources array:
$data.resources = #($data.resources |Where-Object type -ne type2)
Convert the now modified object back to JSON and write to disk:
$data |ConvertTo-Json |Set-Content ./path/to/updatedTemplate.json -Encoding UTF8
I suggest to convert json into PowerShell objects, then make desired changes. then convert back to json if needed.
Example
$root = Get-Content -Path "C:\source.json" | ConvertFrom-Json
$root.resources = $root.resources | where type -eq 'type2'
$root | ConvertTo-Json -Depth 5 | Out-File "C:\destination.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
This question already has an answer here:
Powershell: How to Update/Replace data and values in Json and XML Object
(1 answer)
Closed 4 years ago.
Hello I am trying to modify a JSON file by using PowerShell. I want to pass a variable from PowerhShell that will replace two values(Placeholder1 and Placeholder2)in the JSON file. I have the following for the first value which is not working.
PowerShell
$a = Get-Content $pathToJson -raw | ConvertFrom-Json
$a.update | % {if($_.name -eq 'placeholder1'){$_.name=$record_name}}
$a | ConvertTo-Json -Depth 20 | set-content $pathToJson
JSON
{
"Comment": "Update record for Route 53",
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": "placeholder1",
"Type": "CNAME",
"TTL": 300,
"ResourceRecords": [
{
"Value": "placeholder2"
}
]
}
}
]
}
Instead of converting to-and-from JSON, you can try just replacing the text, like this:
(Get-Content $pathToJson).Replace("placeholder1", $record_name) | Set-Content $pathToJson
You can chain the .Replace() function with another to update placeholder2 with whatever value it should be then.
I have converted the following JSON file to powershell representation object.
{
"computer": [
{
"children": [
{
"children": [ {
"children": [ {
"path": "T:\Dropbox\kvaki.html",
"name": "kvaki",
"type": "url",
"url": "http://example.com"
} ],
"path": "T:\Dropbox\",
"name": "Njusha",
"type": "folder"
}, {
"path": "T:\Dropbox\Europa.html",
"name": "Europa",
"type": "url",
"url": "http://example.com"
}, {
"path": "T:\Dropbox\math.html",
"name": "math",
"type": "url",
"url": "http://example.com"
} ],
"path": "T:\Dropbox\",
"name": "Money",
"type": "folder"
}
],
"full_path_on_file_sys": "T:\Dropbox\"
}
]
}
After doing some computations with powershell representation I would like to save it to file as JSON.
But command $jsonRepresentation | ConvertTo-Json | Out-File "D:\dummy_path\file.json" saves it in this way
{
"computer": [
{
"children": " ",
"full_path_on_file_sys": "T:\Dropbox\"
}
]
}
Question: how to achieve correct saving of complex powershell JSON representation?
-depth argument for ConvertTo-Json solves the issue.
$jsonRepresentation | ConvertTo-Json -depth 100 | Out-File "D:\dummy_path\file.json"
Just pipe it to Set-Content, or Out-File:
Get-Process powershell |
ConvertTo-Json |
Set-Content json.txt
If you want to both view the output and save it to file, you can pipe the tee command.
Get-Process powershell | ConvertTo-Json | Tee-Object json.txt
$json.properties.metadata | ConvertTo-Json -Compress
if you are stuck with PowerShell Version 2, the JSON module of Joel Bennett from the 'PowerShell Code Repository' might help.
1) The below command can be used to convert a json to CSV
Example:
Get-Content package.json | Out-String | ConvertFrom-Json | Select parameter1, parameter2, parameter3 | ConvertTo-Csv -NoTypeInformation | Format-Table >> C:\JenkinsWorkspace\Result.csv
Get-Content: This is like "cat" command in linux which will get all data of file "package.json" and converts from Json (Using ConvertFrom-Json function) extracting the details of only required parameters and then converting them into CSV using "ConvertTo-Csv" function without any unwanted Type Headers and formatting them into Table.
2) The above result can also be formatted into proper csv to view it as Excel format without any duplicates and also having Text-To-Column conversion using below command:
Import-Csv "C:\Result.csv" -delimiter "," | Sort-Object _from -Unique | Export-csv "C:\FINAL_REPORT_$date.csv"
Consider JSON in this format :
"Stuffs": [
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
In PowerShell 3, we can obtain a list of Stuffs :
$JSON = Get-Content $jsonConfigFile | Out-String | ConvertFrom-Json
Assuming we don't know the exact contents of the list, including the ordering of the objects, how can we retrieve the object(s) with a specific value for the Name field ?
Brute force, we could iterate through the list :
foreach( $Stuff in $JSON.Stuffs ) {
But I am hopeful there exists a more direct mechanism ( similar to Lync or Lambda expressions in C# ).
$json = #"
{
"Stuffs":
[
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
}
"#
$x = $json | ConvertFrom-Json
$x.Stuffs[0] # access to Darts
$x.Stuffs[1] # access to Clean Toilet
$darts = $x.Stuffs | where { $_.Name -eq "Darts" } #Darts
I just asked the same question here: https://stackoverflow.com/a/23062370/3532136
It has a good solution. I hope it helps ^^.
In resume, you can use this:
The Json file in my case was called jsonfile.json:
{
"CARD_MODEL_TITLE": "OWNER'S MANUAL",
"CARD_MODEL_SUBTITLE": "Configure your download",
"CARD_MODEL_SELECT": "Select Model",
"CARD_LANG_TITLE": "Select Language",
"CARD_LANG_DEVICE_LANG": "Your device",
"CARD_YEAR_TITLE": "Select Model Year",
"CARD_YEAR_LATEST": "(Latest)",
"STEPS_MODEL": "Model",
"STEPS_LANGUAGE": "Language",
"STEPS_YEAR": "Model Year",
"BUTTON_BACK": "Back",
"BUTTON_NEXT": "Next",
"BUTTON_CLOSE": "Close"
}
Code:
$json = (Get-Content "jsonfile.json" -Raw) | ConvertFrom-Json
$json.psobject.properties.name
Output:
CARD_MODEL_TITLE
CARD_MODEL_SUBTITLE
CARD_MODEL_SELECT
CARD_LANG_TITLE
CARD_LANG_DEVICE_LANG
CARD_YEAR_TITLE
CARD_YEAR_LATEST
STEPS_MODEL
STEPS_LANGUAGE
STEPS_YEAR
BUTTON_BACK
BUTTON_NEXT
BUTTON_CLOSE
Thanks to mjolinor.
David Brabant's answer led me to what I needed, with this addition:
x.Stuffs | where { $_.Name -eq "Darts" } | Select -ExpandProperty Type
Hows about this:
$json=Get-Content -Raw -Path 'my.json' | Out-String | ConvertFrom-Json
$foo="TheVariableYourUsingToSelectSomething"
$json.SomePathYouKnow.psobject.properties.Where({$_.name -eq $foo}).value
which would select from json structured
{"SomePathYouKnow":{"TheVariableYourUsingToSelectSomething": "Tada!"}
This is based on this accessing values in powershell SO question
. Isn't powershell fabulous!
In regards to PowerShell 5.1 ...
Operating off the assumption that we have a file named jsonConfigFile.json with the following content from your post:
{
"Stuffs": [
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
}
This will create an ordered hashtable from a JSON file to help make retrieval easier:
$json = [ordered]#{}
(Get-Content "jsonConfigFile.json" -Raw | ConvertFrom-Json).PSObject.Properties |
ForEach-Object { $json[$_.Name] = $_.Value }
$json.Stuffs will list a nice hashtable, but it gets a little more complicated from here. Say you want the Type key's value associated with the Clean Toilet key, you would retrieve it like this:
$json.Stuffs.Where({$_.Name -eq "Clean Toilet"}).Type
It's a pain in the ass, but if your goal is to use JSON on a barebones Windows 10 installation, this is the best way to do it as far as I've found.
This is my json data:
[
{
"name":"Test",
"value":"TestValue"
},
{
"name":"Test",
"value":"TestValue"
}
]
Powershell script:
$data = Get-Content "Path to json file" | Out-String | ConvertFrom-Json
foreach ($line in $data) {
$line.name
}