首页 > 解决方案 > 从 JSON 阅读器读取时发现意外的“PrimitiveValue”节点。需要一个“StartArray”节点

问题描述

我有一个 Azure AD 应用程序,我需要在使用 Powershell 的服务主体内的 appRoles 部分中添加一个额外的 appRole。我将 Invoke-RestMethod 用于具有以下 API Url 的 Graph API:https ://graph.microsoft.com/beta/servicePrincipals/AppID

Invoke-RestMethod 返回一个 PSCustomObject,然后我在 appRoles 部分添加另一个 PSCustomObject。然后,我将 PSCustomObject 转换为 JSON,并希望将 JSON 写回服务主体。问题是当我想将 JSON 写回服务主体时,我收到错误消息:

Invoke-RestMethod :远程服务器返回错误:(400)错误请求。

我也尝试使用图形资源管理器执行此操作,然后收到错误消息:

“从 JSON 阅读器读取时发现了意外的‘PrimitiveValue’节点。应为‘StartArray’节点。”

我认为 C# 中也存在同样的问题:在 C#中使用 Office 365 API 和 HttpClient 更新电子邮件类别时出现错误请求错误

当我在 Graph Explorer 中执行 Get 时,每个 appRole 都显示如下:

{
  "allowedMemberTypes": [
    "User"
  ],
  "description": "TEST-ALLOWALL",
  "displayName": "TEST-ALLOWALL",
  "id": "00000000-0000-0000-0000-00000000",
  "isEnabled": true,
  "origin": "ServicePrincipal",
  "value": "ARNROLEVALUE"
},

当我执行 Invoke-RestMethod 然后 ConvertTo-Json 时,每个 appRole 都显示如下:

{
  "allowedMemberTypes":  "User",
  "description":  "TEST-ALLOWALL",
  "displayName":  "TEST-ALLOWALL",
  "id":  "00000000-0000-0000-0000-00000000",
  "isEnabled":  true,
  "origin":  "ServicePrincipal",
  "value":  "ARNROLEVALUE"
},

如何确保 Invoke-RestMethod 将 allowedMemberTypes 值类型保留为数组/列表,如 ["User"] 而不是值"User"?

以及如何创建自己的 PSCustomObject allowedMembertypes 值和数组列表,以便将其添加到服务主体?

这是我正在使用的代码

$apiUrl = 'https://graph.microsoft.com/beta/servicePrincipals/000000-0000-0000-0000-00000000000'
$Data = Invoke-RestMethod -Headers $graphAPIReqHeader -Uri $apiUrl -Method Get

$obj = New-Object -TypeName PSObject
$obj | Add-Member -MemberType NoteProperty -Name allowedMemberTypes -Value "User"
$obj | Add-Member -MemberType NoteProperty -Name description -Value $RoleName
$obj | Add-Member -MemberType NoteProperty -Name displayName -value $RoleName
$obj | Add-Member -MemberType NoteProperty -Name id -value $Id
$obj | Add-Member -MemberType NoteProperty -Name isEnabled -value "true"
$obj | Add-Member -MemberType NoteProperty -Name origin -value "ServicePrincipal"
$obj | Add-Member -MemberType NoteProperty -Name value -value $Value

$Data.appRoles += $obj
$NewJson = $Data | ConvertTo-Json
$NewData = Invoke-RestMethod -Headers $graphAPIReqHeader -Uri $apiUrl -Body $NewJson -Method Patch -ContentType 'application/json' 

标签: powershellgraph

解决方案


$input = @"
{
  "allowedMemberTypes": [
    "User"
  ],
   "description": "TEST-ALLOWALL",
   "displayName": "TEST-ALLOWALL",
  "id": "00000000-0000-0000-0000-00000000",
  "isEnabled": true,
  "origin": "ServicePrincipal",
  "value": "ARNROLEVALUE"
}
"@

$jObject = $input | convertfrom-json

$psObj = [Pscustomobject] @{
   AllowedMemberTypes = $jObject.allowedMemberTypes 
}
 $psObj.AllowedMemberTypes.Gettype()

$psObj.AllowedMemberTypes.Gettype()表明它AllowedMemberTypes是数组类型。

你可以在网上找到代码,然后玩弄它。

希望有帮助。


推荐阅读