You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将AWS角色策略文档中的不可读字符转换为可读格式?

解决AWS IAM GetRolePolicyAsync返回URL编码策略文档的问题

要将返回的URL编码策略文档转换为可读的格式化JSON,只需完成两步操作:URL解码和JSON格式化,以下是具体实现方案:

核心代码实现

使用System.Text.Json(.NET Core 3.0+ 内置)

using System;
using System.Net;
using System.Text.Json;

var inlinePolicyDetails = iamClient.GetRolePolicyAsync(new GetRolePolicyRequest
{
    RoleName = "xyzRole",
    PolicyName = "xyzPolicy"
}).GetAwaiter().GetResult();

// 1. 对URL编码的PolicyDocument进行解码
var decodedRawJson = WebUtility.UrlDecode(inlinePolicyDetails.PolicyDocument);

// 2. 格式化JSON字符串,提升可读性
var serializeOptions = new JsonSerializerOptions { WriteIndented = true };
var formattedPolicyJson = JsonSerializer.Serialize(
    JsonSerializer.Deserialize<object>(decodedRawJson), 
    serializeOptions
);

Console.WriteLine(formattedPolicyJson);

使用Newtonsoft.Json(第三方库)

如果项目中已经使用Newtonsoft.Json,也可以用以下方式实现:

using System;
using System.Net;
using Newtonsoft.Json;

var inlinePolicyDetails = iamClient.GetRolePolicyAsync(new GetRolePolicyRequest
{
    RoleName = "xyzRole",
    PolicyName = "xyzPolicy"
}).GetAwaiter().GetResult();

var decodedRawJson = WebUtility.UrlDecode(inlinePolicyDetails.PolicyDocument);
var formattedPolicyJson = JsonConvert.SerializeObject(
    JsonConvert.DeserializeObject(decodedRawJson), 
    Formatting.Indented
);

Console.WriteLine(formattedPolicyJson);

效果说明

执行上述代码后,原本的URL编码字符串会被转换为你期望的格式化JSON:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "XYZ:ABCD"
      ],
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}

内容的提问来源于stack exchange,提问作者Shankar S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 13:07:19