![](/img/trans.png)
[英]How can I make my json object's field name a value with in an object array with javascript?
[英]Powershell: High Performing conversion of Name and Value Array into Parseable format - How can I make this Faster
當我希望從 JSON 有效負載$JSON
制作一個容易/快速的可解析對象/PSCustomObject 時,如何使我的代碼性能更高?
我收到的 PAYLOAD 結構的一個示例是:
[
{
"name": "system.enablenetflow",
"value": "false"
},
{
"name": "system.deviceGroupId",
"value": "186,3060"
},
{
"name": "system.prefcollectorid",
"value": "144"
},
{
"name": "system.collectorplatform",
"value": "windows"
}
]
如您所見,它的格式非常煩人。
請注意,我嘗試解析的有效負載要大得多,並且數量從 500 個這些名稱/值對象到 50000 個不等,而不僅僅是上面列出的 4 個。
################################################# #########################
我的目標
把它變成一個鍵值對場景,以便以后更容易解析
不是這個:
使用 JSON 我必須做$JSON.where({$_.name -eq "system.enablenetflow"}).value
是的:
我希望結尾 state 是我創建的新變量$obj
將讓我獲得$obj."system.enablenetflow"
################################################# #########################
我目前的嘗試非常慢
我做了以下事情:
$obj
$JSON
變量執行了 foreach 方法$obj
這是我的代碼示例:
$obj = [PSCustomObject] @{}
$json.foreach({
$thisitem = $_
$obj | Add-member -NotePropertyName $($thisitem.name) -NotePropertyValue $($thisitem.name)
})
我怎樣才能讓它更快?
# Sample input JSON.
$json = @'
[
{
"name": "system.enablenetflow",
"value": "false"
},
{
"name": "system.deviceGroupId",
"value": "186,3060"
},
{
"name": "system.prefcollectorid",
"value": "144"
},
{
"name": "system.collectorplatform",
"value": "windows"
}
]
'@
# Initialize the (ordered) result hashtable.
$result = [ordered] @{}
# Note: In PowerShell (Core) 7+, add -AsHashTable to the ConvertFrom-Json
# call for additional performance gain, combined with -AsArray,
# in which case you don't need the `(...)` around the call anymore.
foreach ($element in (ConvertFrom-Json $json)) {
$result[$element.name] = $element.value
}
上面創建了一個(有序的)哈希表而不是一個[pscustomobject]
實例 - 特別是如果后者是通過Add-Member
調用迭代構造的。
哈希表比[pscustomobject]
實例更輕量且構建速度更快。
使用foreach
循環而不是通過ForEach-Object
在管道中處理ConvertFrom-Json
output 也可以加快處理速度。
PowerShell 允許您在哈希表中也使用熟悉的點表示法; 因此,例如,在運行上述內容后,您將獲得:
PS> $result.'system.collectorplatform'
windows
如果您確實需要$result
作為[pscustomobject]
實例,您可以簡單地將完全填充的哈希表轉換為該類型:
PS> $obj = [pscustomobject] $result; $obj.'system.collectorplatform'
windows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.