我有一個 JSON 檔案需要有條件地編輯。它可能是一個空物件:{}
或者它可能包含其他資料。
我需要查看我要添加的資料是否已經存在,如果不存在,請將其添加到該 JSON 檔案中。
有問題的內容如下所示(整個 JSON 檔案):
{
{
"2020.3.19f1": {
"version": "2020.3.19f1",
"location": [
"C:\\Program Files\\Unity\\Hub\\Editor\\2020.3.19f1\\Editor\\Unity.exe"
],
"manual": true
}
}
在這種情況下,如果“2020.3.19f”不存在,我需要添加該塊。我看了這些檔案,但真的很迷茫。任何提示表示贊賞:https : //docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-7.2 這似乎很接近,但我對檢查語法迷失了方向為空或空,以及如何轉換為 PS:PowerShell:按欄位值檢索 JSON 物件
編輯:因此,例如,如果原始檔案是:
{}
然后我需要用以下內容覆寫該檔案:
{
{
"2020.3.19f1": {
"version": "2020.3.19f1",
"location": [
"C:\\Program Files\\Unity\\Hub\\Editor\\2020.3.19f1\\Editor\\Unity.exe"
],
"manual": true
}
}
如果檔案已經包含一些東西,我需要保留它,只需添加新塊:
{
{
"2019.4.13f1": {
"version": "2019.4.13f1",
"location": [
"C:\\Program Files\\Unity\\Hub\\Editor\\2019.3.13f1\\Editor\\Unity.exe"
],
"manual": true
},
{
"2020.3.19f1": {
"version": "2020.3.19f1",
"location": [
"C:\\Program Files\\Unity\\Hub\\Editor\\2020.3.19f1\\Editor\\Unity.exe"
],
"manual": true
}
}
FWIW:我確實找到了我需要的條件:
$FileContent = Get-Content -Path "C:\Users\me\AppData\Roaming\UnityHub\editors.json" -Raw | ConvertFrom-Json
if ( ($FileContent | Get-Member -MemberType NoteProperty -Name "2020.3.19f1") -ne $null )
{
echo "it exists"
}
else
{
echo "add it"
# DO SOMETHING HERE TO CREATE AND (OVER)WRITE THE FILE
}
uj5u.com熱心網友回復:
您可以將 json 轉換為物件并根據需要添加屬性。
$json = @"
{
"2020.3.19f2": {
"version": "2020.3.19f2",
"location": [
"C:\\Program Files\\Unity\\Hub\\Editor\\2020.3.19f2\\Editor\\Unity.exe"
],
"manual": true
}
}
"@
$obj = ConvertFrom-Json $json
if (-not $obj.'2020.3.19f1') {
Add-Member -InputObject $obj -MemberType NoteProperty -Name '2020.3.19f1' -Value $(
New-Object PSObject -Property $([ordered]@{
version = "2020.3.19f1"
location = @("C:\Program Files\Unity\Hub\Editor\2020.3.19f1\Editor\Unity.exe")
manual = $true
})
) -Force
$obj | ConvertTo-Json
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/363475.html
