我有一个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这看起来很接近,但我对检查null或空的语法以及如何将其转换为PS:PowerShell : retrieve JSON object by field value感到迷惑
Edit:例如,如果原始文件是:
{}然后我需要用以下命令覆盖该文件:
{
{
"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
}发布于 2021-11-22 19:25:35
您可以将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://stackoverflow.com/questions/70070970
复制相似问题