Powershell:如何在Json和XML对象中更新/替换数据和值 [英] Powershell: How to Update/Replace data and values in Json and XML Object
问题描述
所以我在这里有一个问题,我似乎无法弄清楚如何更新对象中的数据值
So I am having a bit of a problem here, I can't seem to figure out how to update data values in an Object
因此,例如说FOLLOWING json
so lets say for example the FOLLOWING 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
I have Powershell read it smoothly with convertfrom-json
我将如何执行以下操作:
A)将橙色"从"2"更改为"100"
A) Change "Oranges" from "2" to "100"
B)2号会议室中的购物篮",从假"到真"
B) "Baskets" in Room 2 from "false" to "true"
C)在Room1的糖果"中添加泡泡糖"
C) add "bubblegum" to "candies" in Room1
如何在不重写整个json或对象的情况下更新此内容?
推荐答案
JSON成为带有嵌套对象的自定义对象,因此确实非常简单.首先,让我们通过在Apples值之后添加逗号来修复JSON,然后将其转换为对象...
The JSON becomes a custom object with nested objects, so really it is fairly simple. To start, let's fix the JSON by adding a comma after the Apples value, and convert it to an object...
$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,我们只需更改值即可:
Then if we want to update Oranges from 2 to 100 we simply change the value:
$JSON.Fruits.Oragnes = 100
类似地,我们可以通过简单地列出场所,将其传递到Where
语句以获取正确的房间并在ForEach
循环中修改值来修改Room 2.
Similarly we can modify the Room 2 by simply listing the Places, passing it to a Where
statement to get the right room, and modify the value in a ForEach
loop.
$JSON.Places.Places | Where{$_.name -eq 'Room 2'} | ForEach{$_.Baskets = 'true'}
最后,由于candies
在JSON中定义为数组,因此我们可以简单地将所需的糖果添加到数组中.
Lastly, since candies
is defined as an array in the JSON we can simply add the desired candy to the array.
$JSON.Places.Places | Where{$_.name -eq 'Room 1'} | ForEach{$_.CandyTypesPresent.candies += 'bubblegum'}
这篇关于Powershell:如何在Json和XML对象中更新/替换数据和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!