I have a test.json file which has the below structure:
{
"name": "test",
"class": "4",
"exam": "test",
"marks": "4"
}
I want to remove some pairs from it like exam and class, and ultimately it should look like below:
{
"name": "test",
"marks": "4"
}
How can I do it from PowerShell?
Your post was not completely clear if you wanted to remove certain keys, or if you only wanted to retain marks and name. The code below performs the latter:
Get-Content 'test.json' -Raw |
ConvertFrom-Json |
Select-Object name, marks |
ConvertTo-Json
Result:
{
"name": "test",
"marks": "4"
}
powershell cmd:
$obj = Get-Content .\aaa.json | ConvertFrom-Json
$obj.psobject.properties.remove('exam')
$obj.psobject.properties.remove('class')
$obj | ConvertTo-Json
output:
{
"name": "test",
"marks": "4"
}
Related
I have the below JSON which is just a bit of the file but illustrates it.
I am not that experienced with JSON and I have tried a lot of the examples that I could find but they only seem to show JSON that is just key/value pairs. I've seen a few to target arrays but I cant translate them to my particular JSON
for example I'm trying to get that the 'SavedPlayerDataVersion' is equal to 8 into a variable and I've put it into an object but I cant figure out how to target that particular item within the array and object
could anyone point me in the right direction please?
Thank you
{
"profileVersion": 1,
"profile": {
"id": 0,
"class": "PrimalPlayerDataBP_C",
"names": ["PrimalPlayerDataBP_C_29", "ArkGameMode", "PersistentLevel", "Aberration_P", "/Game/Maps/Aberration/Aberration_P"],
"properties": [{
"name": "SavedPlayerDataVersion",
"type": "IntProperty",
"value": 8
}, {
"name": "HexagonCount",
"type": "IntProperty",
"value": 106860
}, {
"name": "MyPersistentBuffDatas",
"type": "ArrayProperty",
"arrayType": "ObjectProperty",
"value": [1, 2, 3, 4]
}],
"extra": null
}
}
"type": "IntProperty",
"value": 8
}, {
"name": "HexagonCount",
"type": "IntProperty",
"value": 6800
}, {
"name": "NumChibiLevelUpsData",
"type": "IntProperty",
"value": 2
}, {
"name": "MyData",
"type": "StructProperty",
"structType": "PrimalPlayerDataStruct",
"value": [{
"name": "PlayerDataID",
"type": "UInt64Property",
"value": 656195017
}, {
"name": "UniqueID",
"type": "StructProperty",
"structType": "UniqueNetIdRepl",
"value": {
"unk": 8,
"netId": "76561198046328344"
}
}
I have edited the question after the original answers as I realised that what I also needed to access was a 'level' deeper. so it would be getting at "PlayerDataID"
I tried $value = ($jsonobj.profile.properties.mydata | Where-Object { $_.name -eq "PlayerDataID" }).value but that isnt getting it for me
JSON is exactly key-value pairs, so handling it like an object in PowerShell is the way to go. Start with ConvertFrom-Json and put the result in a variable, let's say $myJson.
$myJson.profile.class would net you PrimalPlayerDataBP_C. That's how you access nested properties. As for the arrays, you can iterate through them with foreach, get specific values with where or select, depends on what you need actually.
# This one returns the version number
$version = ($myJson.profile.properties | Where {$_.name -eq "SavedPlayerDataVersion"}).value
# This one checks whether version is 8
$isVersion8 = $NULL -ne `
($myJson.profile.properties | Where {$_.name -eq "SavedPlayerDataVersion" -and $_.value -eq 8})
Be careful when accessing array items using their index, as you never can be sure that the item with a specific index is the one you're looking for.
As I'm writing this answer, #Theo beat me to it, so kudos to him for the one-liner.
EDIT:
Including a step-by-step example for clarity's sake. You can do the same with fewer lines.
# Get an array of properties
$properties = $myJson.profile.properties
# Select the property with the required name from the array
$myData = $properties | Where {$_.name -eq "MyData"}
# MyData is multivalued, so need to use 'Where' again
$playerDataId = $myData.value | Where {$_.name -eq "PlayerDataID"}
# Value you are looking for
$playerDataId.value
You can get the value you seek with a one-liner.
For demo I'm using a Here-String for your json data, but probably you would read that from file with $data = Get-Content -Path 'thefile.json' -Raw | ConvertFrom-Json
$data = #'
{
"profileVersion": 1,
"profile": {
"id": 0,
"class": "PrimalPlayerDataBP_C",
"names": ["PrimalPlayerDataBP_C_29", "ArkGameMode", "PersistentLevel", "Aberration_P", "/Game/Maps/Aberration/Aberration_P"],
"properties": [{
"name": "SavedPlayerDataVersion",
"type": "IntProperty",
"value": 8
}, {
"name": "HexagonCount",
"type": "IntProperty",
"value": 106860
}, {
"name": "MyPersistentBuffDatas",
"type": "ArrayProperty",
"arrayType": "ObjectProperty",
"value": [1, 2, 3, 4]
}],
"extra": null
}
}
'# | ConvertFrom-Json
Then, to get the value from property with name "SavedPlayerDataVersion" you simply do:
$value = ($data.profile.properties | Where-Object { $_.name -eq "SavedPlayerDataVersion" }).value
Variable $value will now contain 8
Simple example:
$json = '{ "one": 1, "two": 2 }'
$data = $json | ConvertFrom-Json | Select one
$myVal = $data.one
$myVal
The printed output will be 1
In your case:
$json = '{
"profileVersion": 1,
"profile": {
"id": 0,
"class": "PrimalPlayerDataBP_C",
"names": ["PrimalPlayerDataBP_C_29", "ArkGameMode", "PersistentLevel", "Aberration_P", "/Game/Maps/Aberration/Aberration_P"],
"properties": [{
"name": "SavedPlayerDataVersion",
"type": "IntProperty",
"value": 8
}, {
"name": "HexagonCount",
"type": "IntProperty",
"value": 106860
}, {
"name": "MyPersistentBuffDatas",
"type": "ArrayProperty",
"arrayType": "ObjectProperty",
"value": [1, 2, 3, 4]
}],
"extra": null
}}'
$data = $json | ConvertFrom-Json | Select -expand profile | Select -expand properties | Select name, type, value
$myVal = $data[0].value
$myVal
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.
I am trying to get data from my json file but my code is still not working. Do you have any suggestion ?
JSON file :
"nodes": [
{
"id": "elfe",
"apps": [
{
"id": "man1",
"age" = "5"
"power" ="strenght"
},
{
"id": "man2",
"age" = "10"
"power" ="strenght"
}],
"id": "monster",
"apps": [
{
"id": "man3",
"age" = "5"
"power" ="strenght"
},
{
"id": "man4",
"age" = "10"
"power" ="strenght"
}],
And there, my code in PowerShell. I just want to get man1, man2, man3, man4 values in my file for each id elfe and monster like that :
man1
man2
in one file and in the other file:
man3
man4
My batch script :
Powershell -Nop -C "(Get-Content .\config.json |ConvertFrom-Json).Nodes | Select-Object -ExpandProperty id | Where-Object id -eq elfe" >> file.txt
EDIT : I can't modify my JSON file...
Your json is not valid, below is corrected version with data extraction:
$json = #"
{
"nodes":[
{
"id":"elfe",
"apps":[
{
"id":"man1",
"age":5,
"power":"strenght"
},
{
"id":"man2",
"age":10,
"power":"strenght"
}]},
{ "id":"monster",
"apps":[
{
"id":"man3",
"age" :"5",
"power":"strenght"
},
{
"id":"man4",
"age":"10",
"power":"strenght"
}]}
]}
"#
$data = $json | ConvertFrom-Json
$data.nodes | where {$_.id -eq "elfe"} | foreach {$_.apps.id >> "elfe.txt"}
But probably you just had troubles with quoting that command. Below is a working version. I replaced >> with tee - it will overwrite output file and also prints results on the screen.
powershell -nop -c "(cat test.json | ConvertFrom-Json).nodes | where {$_.id -eq 'elfe'} | foreach {$_.apps.id} | tee out.txt"
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
}