Hello I'm trying to use convertto-json to create a json file from another output and save it but I'm getting a bad json format
Here is my function
$output.value | ForEach-Object {
"{"+"id"+':'+ $_.id+','+"outcome" +':'+ '"'+$_.results.outcome+'"'+','+"idtc"+':' +$_.testCaseReference.id + "}"
} | ConvertTo-Json| Out-File -FilePath .\tfs.json
Here is the outcome of the tfs.json
[
"{id:11431,outcome:\"passed\",idtc:70155}",
"{id:11432,outcome:\"unspecified\",idtc:70156}",
"{id:11433,outcome:\"failed\",idtc:70157}",
"{id:11434,outcome:\"unspecified\",idtc:70158}"
]
Can anyone help why it does appear in that way instead of
[
{"id":11431,"outcome":"passed","idtc":70155"},
{"id":11432,"outcome":"unspecified","idtc":70156"},
{"id":11433,"outcome":"failed","idtc":70157"},
{"id":11434,"outcome":"unspecified","idtc":70158"}
]
The output you're receiving from ConvertTo-JSON is pretty much expected. You're passing a string to the cmdlet hence it is returning a string as JSON.
Try this instead:
$output.value | ForEach-Object {
[pscustomobject]#{
id = $_.id
outcome = $_.results.outcome
idtc = $_.testCaseReference.id
}
} | ConvertTo-Json | Out-File -FilePath .\tfs.json
Related
My current code:
Powershell -Noprofile "(Get-Content 'allacts.txt' | ConvertFrom-Json).activityid | Out-File -FilePath ids%filenum%.txt"
This queries the JSON file (allacts.txt) and extracts a single value, activityid.
However, I don't want all the activityids, just the ones where the value attendedpeoplecount is higher than 0. How can I work that if logic into this command?
Sample:
[
{
"activityid": 610228,
"attendedpeoplecount": 0
},
{
"activityid": 568168,
"attendedpeoplecount": 36
}
]
Current command on the above json would return
610228
568168
The desired output would be
568168
Using the Where-Object Cmdlet should get you what you need.
Powershell -Noprofile "((Get-Content 'allacts.txt' | ConvertFrom-Json) | Where-Object { $_.attendedpeoplecount -gt 0 }).activityid | Out-File -FilePath ids%filenum%.txt"
Update: Wrapped Get-Content and ConvertFrom-Json in parenthesis
I am trying to add value in key pair json file using Powershell. I am getting an error. Need some guidance on PS Scripting.
Powershell 5.1 version and json file with key pair inside it.
MYJSON File:
{ "Theme":{"Res_List": {
"Method": "POST",
"Name":""}}}
PowerShell Script:
$file_path="C:\Users\RelativeConfig.json"
$json = Get-Content $file_path | Out-String | ConvertFrom-Json
$timestamp = Get-Date -Format ddMMHHmm
$namevalue = 'resource'+$timestamp+'e3'
echo $namevalue ##prints resource16sep2019 I want this to write in json as value for Name Key
$files = $json | Get-Member -MemberType Properties | Select-Object - ExpandProperty Name
$result = Foreach ($file in $json)
{
if ($file.Name -eq "Name") { $file.Value = $namevalue}
}
$result | ConvertTo-Json | Set-Content $json
Error:
No error but json is not updated with new values.
Expected:
{ "Theme":{"Res_List": {
"Method": "POST",
"Name":"resource16sep2019 "}}}
Actual:
{ "Theme":{"Res_List": {
"Method": "POST",
"Name":""}}}
To update your value in json you can do something like below
$bucket_name = "resource16sep2019" ## I want this to write in json as value for Name Key
$json.Theme.Res_List.Name = $bucket_name
It will directly replace the $bucket_name value with the Name value in JSON.
If you want to write this to the respective file use the below command,
$json | ConvertTo-Json -depth 32| set-content $file_path
Hope it helps! Cheers
I'm trying to update a boolean value inside a JSON formated file using powershell but I'm not getting the required output.
From the below,
{
"setComputerName": false,
"setWallpaper": true
}
I would like to get the output as,
{
"setComputerName": true,
"setWallpaper": true
}
Below is my script,
$file = Get-Content 'C:\temp\Config.json' -raw | ConvertFrom-Json
$file = $file.setComputerName = 'true'
$file | ConvertTo-Json | set-content 'C:\temp\Config1.json'
All you have to do once you import your json is.
$file.setComputerName=$true
$file | ConvertTo-Json | set-content 'C:\temp\Config1.json'
You were trying to set the value as a string and it needs to be boolean, so you need to use $true or $false in order to set those values.
Hope this helps!
I have a sample JSON-formatted here which converts fine if I use something like: https://konklone.io/json/
I've tried the following code in PowerShell:
(Get-Content -Path $pathToJsonFile | ConvertFrom-Json)
| ConvertTo-Csv -NoTypeInformation
| Set-Content $pathToOutputFile
But the only result I get is this:
{"totalCount":19,"resultCount":19,"hasMore":false,"results":
How do I go about converting this correctly in PowerShell?
By looking at just (Get-Content -Path $pathToJsonFile) | ConvertFrom-Json it looks like the rest of the JSON is going in to a results property so we can get the result I think you want by doing:
((Get-Content -Path $pathToJsonFile) | ConvertFrom-Json).results |
ConvertTo-Csv -NoTypeInformation |
Set-Content $pathToOutputFile
FYI you can do ConvertTo-Csv and Set-Content in one move with Export-CSV:
((Get-Content -Path $pathToJsonFile) | ConvertFrom-Json).results |
Export-CSV $pathToOutputFile -NoTypeInformation
You have to select the results property inside your CSV using the Select-Object cmdlet together with the -expand parameter:
Get-Content -Path $pathToJsonFile |
ConvertFrom-Json |
Select-Object -expand results |
ConvertTo-Csv -NoTypeInformation |
Set-Content $pathToOutputFile
I was getting my json from a REST web api and found that the following worked:
Invoke-WebRequest -method GET -uri $RemoteHost -Headers $headers
| ConvertFrom-Json
| Select-Object -ExpandProperty <Name of object in json>
| ConvertTo-Csv -NoTypeInformation
| Set-Content $pathToOutputFile
I end up with a perfectly formatted csv file
Trying to use Mark Wrang's answer failed for me. While Piemol's comment from Jan 30 '19 solved a basic problem with Mark Wrang's answer, it also didn't work for me.
JSON strings do not always represent rectangular data sets. They may contain ragged data. For example, the Power BI activities log outputs JSON that contains different members depending on variables like what activities occurred in the requested data or what features were available at the time.
Using Piemol's comment, I processed this JSON:
[
{
"a": "Value 1",
"b": 20,
"g": "Arizona"
},
{
"a": "Value 2",
"b": 40,
"c": "2022-01-01T11:00:00Z"
},
{
"a": "Value 3",
"d": "omicron",
"c": "2022-01-01T12:00:00Z"
},
{
"a": "Value 4",
"b": 60,
"d": "delta",
"e": 14,
"c": "2022-01-01T13:00:00Z"
}
]
The script produced this CSV:
"a","b","g"
"Value 1","20","Arizona"
"Value 2","40",
"Value 3",,
"Value 4","60",
Notice that columns c, d, and e are missing. It appears that Export-CSV uses the first object passed to determine the schema for the CSV to output.
To handle this, use the UnifyProperties function:
function UnifyProperties {
$Names = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
$InputCollected = #($Input)
$InputCollected.ForEach({
foreach ($Name in $_.psobject.Properties.Name) { $Null = $Names.Add($Name) }
})
$inputCollected | Select-Object #($Names)
}
$pathToInputFolder = (New-Object -ComObject Shell.Application).NameSpace('shell:Downloads').Self.Path + "\" + "PowerBIActivities\combined\"
$pathToInputFile = $pathToInputFolder + "Activities.json"
$pathToOutputFile = $pathToInputFolder + "Activities.csv"
$content = Get-Content -Path $pathToInputFile -Raw
$psObj = ConvertFrom-Json -InputObject $content
$psObj | UnifyProperties | Export-CSV $pathToOutputFile -NoTypeInformation
I have a CSV file that I am trying to convert to JSON using PowerShell.
The CSV file contains the following data.
web_url.csv
wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/
I would like to convert to json in the following format. Similarly how do you convert this json back to original csv in the format shown above?
web_url.json
{
"wikipedia": "https://en.wikipedia.org/wiki/%s",
"wolframalpha": "http://www.wolframalpha.com/input/?i=%s",
"drive": "http://www.drive.google.com/"
}
When I run the command,
Get-Content -path web_url.csv | ConvertFrom-Csv -Delimiter ',' |
ConvertTo-Json
it returns the following output which is not what I want.
[
{
"wikipedia": "wolframalpha",
"https://en.wikipedia.org/wiki/%s": "http://www.wolframalpha.com/input/?i=%s"
},
{
"wikipedia": "drive",
"https://en.wikipedia.org/wiki/%s": "http://www.drive.google.com/"
}
]
# PowerShell script
import-csv "SampleInput.csv" | ConvertTo-Json | Add-Content -Path "output.json"
Your csv doen't look like a "proper" csv to me: columns are swapped with rows. If you have control over input file, you may fix it there already:
#'
wikipedia,wolframalpha,drive
https://en.wikipedia.org/wiki/%s,http://www.wolframalpha.com/input/?i=%s,http://www.drive.google.com/
'# | ConvertFrom-Csv | ConvertTo-Json
If that is not possible, you just have to perform some extra steps to get what you need:
$propertyList = #'
wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/
'# | ConvertFrom-Csv -Header Name, Value
$properties = [ordered]#{}
foreach ($property in $propertyList) {
$properties.Add($property.Name, $property.Value)
}
New-Object PSObject -Property $properties | ConvertTo-Json
And back, again - some extra work is required:
(#'
{
"wikipedia": "https://en.wikipedia.org/wiki/%s",
"wolframalpha": "http://www.wolframalpha.com/input/?i=%s",
"drive": "http://www.drive.google.com/"
}
'# | ConvertFrom-Json).PSObject.Properties |
Select-Object Name, Value |
ConvertTo-Csv -NoTypeInformation |
Select-Object -Skip 1
what about this ?
$csv=#"
wikipedia,https://en.wikipedia.org/wiki/%s
wolframalpha,http://www.wolframalpha.com/input/?i=%s
drive,http://www.drive.google.com/
"#
$obj= $csv |convertfrom-csv -delim ',' -Header "name","url"
#$obj
$json=$obj |convertto-json
#$json
$csv2 =$json |convertfrom-json |select -expand syncroot |convertto-csv -NoTypeInformation -Delimiter ','
#$csv2