我正在使用RESTAPI从设备中收集原始文本中的数据,我想替换其中的特定文本块。
我对类型不太满意,而且从几个小时开始就一直坚持下去。
让我们说这是我的原文:
{
"type": "V9",
"firmware": {
"manageFirmware": false,
"reapplyState": "NotApplying"
},
"inProgress": false,
"connectionSettings": {
"reapplyState": "NotApplying",
"connections": [
"@{id=1; name=PR_1; state=Deployed; status=OK}",
"@{id=2; name=PR_2; state=Deployed; status=OK}",
"@{id=3; name=SN_1; state=Reserved; status=Unknown;}",
"@{id=4; name=SN_2; state=Reserved; status=Unknown;}"
]
},
"Tag": "123456"}
我想替换"connections" :
之后的块:
[ "@{id=1; name=PR_1; state=Deployed; status=OK}",
"@{id=2; name=PR_2; state=Deployed; status=OK}",
"@{id=3; name=SN_1; state=Reserved; status=Unknown;}",
"@{id=4; name=SN_2; state=Reserved; status=Unknown;}"
]
在我当前可以收集的另一个文本块中,让我们说这个:
[
{
"id": 1,
"name": "PR_1",
"state": "Deployed",
"status": "OK",
},
{
"id": 2,
"name": "PR_2",
"state": "Deployed",
"status": "OK",
},
{
"id": 3,
"name": "SN_1",
"state": "Reserved",
"status": "Unknown",
},
{
"id": 4,
"name": "SN_2",
"state": "Reserved",
"status": "Unknown",
}
]
我的目标是删除"@
,将=
替换为:
,并在行尾删除}
。
我已经使用-Replace
选项尝试了一些操作,但这并不是很确定。
也尝试过使用一些正则表达式,但是我为此感到非常挣扎。
答案 0 :(得分:1)
看起来提供的json已从psobject转换为深度为2的json。此代码会将其放回对象中,并将hashtables解析为connections属性的对象,然后将其深度转换回json之三,应该会得到您想要的
$json = @'
{
"type": "V9",
"firmware": {
"manageFirmware": false,
"reapplyState": "NotApplying"
},
"inProgress": false,
"connectionSettings": {
"reapplyState": "NotApplying",
"connections": [
"@{id=1; name=PR_1; state=Deployed; status=OK}",
"@{id=2; name=PR_2; state=Deployed; status=OK}",
"@{id=3; name=SN_1; state=Reserved; status=Unknown;}",
"@{id=4; name=SN_2; state=Reserved; status=Unknown;}"
]
},
"Tag": "123456"}
'@
$obj = $json | ConvertFrom-Json
$obj.connectionSettings.connections = $obj.connectionSettings.connections | % {
[pscustomobject](iex ($_ -replace '(?<=[=])([^;}]*)(?=[;}])', "'`$1'"))
}
$newjson = $obj | ConvertTo-Json -Depth 3
$newjson