gpt4 book ai didi

json - Powershell:如何更新/替换 Json 和 XML 对象中的数据和值

转载 作者:行者123 更新时间:2023-12-02 09:02:47 24 4
gpt4 key购买 nike

所以我在这里遇到了一些问题,我似乎不知道如何更新对象中的数据值

所以我们可以说以下 json

{
"People": 263,
"Hungry": true,
"Fruits": {
"Apples": 1 "Oranges": 2
},
"Places": {
"Places": [{
"Baskets": "true",
"name": "Room 1",
"candycount": 1500,
"candytypespresent": {
"candies": [
"caramel"
]
}

},
{

"Baskets": "false",
"name": "Room 2",
"candycount": 2000,
"candytypespresent": {
"candies": [
"caramel",
"jawbreaker",
"butterscotch"
]
}
}
]
}
}

我让 Powershell 使用 convertfrom-json 顺利读取它

我将如何执行以下操作:

A) 将“橙子”从“2”更改为“100”

B) 2 号房间的“篮子”从“假”变为“真”

C) 将“泡泡糖”添加到 Room1 中的“糖果”

如何在不重写整个 json 或对象的情况下更新它

最佳答案

JSON 成为具有嵌套对象的自定义对象,因此实际上它相当简单。首先,我们通过在 Apples 值后添加逗号来修复 JSON,并将其转换为对象...

$JSON = @'
{
"People": 263,
"Hungry": true,
"Fruits": {
"Apples": 1,
"Oranges": 2
},
"Places": {
"Places": [
{
"Baskets": "true",
"name": "Room 1",
"candycount": 1500,
"candytypespresent": {
"candies": [
"caramel"
]
}

},
{

"Baskets": "false",
"name": "Room 2",
"candycount": 2000,
"candytypespresent": {
"candies": [
"caramel",
"jawbreaker",
"butterscotch"
]
}
}
]
}
}
'@ | ConvertFrom-JSON

然后,如果我们想要将 Oranges 从 2 更新为 100,我们只需更改该值即可:

$JSON.Fruits.Oranges = 100

类似地,我们可以通过简单地列出 Places、将其传递给 Where 语句来获取正确的房间来修改 Room 2,并修改 ForEach 循环中的值.

$JSON.Places.Places | Where{$_.name -eq 'Room 2'} | ForEach{$_.Baskets = 'true'}

最后,由于 candies 在 JSON 中被定义为数组,我们可以简单地将所需的糖果添加到数组中。

$JSON.Places.Places | Where{$_.name -eq 'Room 1'} | ForEach{$_.CandyTypesPresent.candies += 'bubblegum'}

关于json - Powershell:如何更新/替换 Json 和 XML 对象中的数据和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45067317/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com