簡體   English   中英

C#解析Azure策略規則json以創建樹

[英]c# parsing azure policy rule json to make a tree

我想通過轉到每個根級別將Newtonsoft.Json.Linq的JSON解析為樹格式。

我面臨的實際問題是allOf內的內容沒有被打印出來,它在JObject中的InvalidCast異常。 我需要幫助來打印控制台應用程序中的所有父元素和子元素。

這是JSON:

{
  "properties": {
    "displayName": "Audit if Key Vault has no virtual network rules",
    "policyType": "Custom",
    "mode": "Indexed",
    "description": "Audits Key Vault vaults if they do not have virtual network service endpoints set up. More information on virtual network service endpoints in Key Vault is available here: _https://docs.microsoft.com/en-us/azure/key-vault/key-vault-overview-vnet-service-endpoints",
    "metadata": {
      "category": "Key Vault",
      "createdBy": "",
      "createdOn": "",
      "updatedBy": "",
      "updatedOn": ""
    },
    "parameters": {},
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.KeyVault/vaults"
          },
          {
            "anyOf": [
              {
                "field": "Microsoft.KeyVault/vaults/networkAcls.virtualNetworkRules[*].id",
                "exists": "false"
              },
              {
                "field": "Microsoft.KeyVault/vaults/networkAcls.virtualNetworkRules[*].id",
                "notLike": "*"
              },
              {
                "field": "Microsoft.KeyVault/vaults/networkAcls.defaultAction",
                "equals": "Allow"
              }
            ]
          }
        ]
      },
      "then": {
        "effect": "audit"
      }
    }
  },
  "id": "/subscriptions/xxxxxx/providers/Microsoft.Authorization/policyDefinitions/wkpolicydef",
  "type": "Microsoft.Authorization/policyDefinitions",
  "name": "xyz"
}

而我的代碼:

static JmesPath jmes = new JmesPath();
static void Main(string[] args)
    {
        string policyStr = "JSON GIVEN IN THE DESCRIPTION";
        string str = jmes.Transform(policyStr, "properties.policyRule.if");
        Convert(str);
    }

    public static void Convert(string json)
    {
        dynamic myObj = JsonConvert.DeserializeObject(json);
        PrintObject(myObj, 0);

        Console.ReadKey();
    }

    private static void PrintObject(JToken token, int depth)
    {
        if (token is JProperty)
        {
            var jProp = (JProperty)token;
            var spacer = string.Join("", Enumerable.Range(0, depth).Select(_ => "\t"));
            var val = jProp.Value is JValue ? ((JValue)jProp.Value).Value : "-";

            Console.WriteLine($"{spacer}{jProp.Name}  -> {val}");


            foreach (var child in jProp.Children())
            {
                PrintObject(child, depth + 1);
            }
        }
        else if (token is JObject)
        {
            foreach (var child in ((JObject)token).Children())
            {
                PrintObject(child, depth + 1);
            }
        }
    }

我已經安裝了JMESPath.Net NuGet軟件包。 演示在這里擺弄。

您的基本問題是,在PrintObject(JToken token, int depth) ,您不考慮傳入tokenJArray

if (token is JProperty)
{
}
else if (token is JObject)
{
}
// Else JArray, JConstructor, ... ?

由於"allOf"的值是一個數組,因此您的代碼不執行任何操作:

{
  "allOf": [ /* Contents omitted */ ]
}

最小的修復方法是檢查JContainer而不是JObject ,但是,這不能處理包含原始值的數組的情況,因此不能視為適當的修復方法。 (演示小提琴在這里 #1。)

相反,在遞歸代碼中,您需要處理JContainer所有可能的子類,包括JObjectJArrayJProperty和(也許) JConstructor 但是,具有兩個層次結構的JArray與僅具有一個層次結構的JObject之間的不一致會使編寫此類遞歸代碼變得煩人。

一種以更JProperty方式處理數組和對象的可能解決方案是完全隱藏JProperty的存在,並表示對象是容器,其子項按名稱索引,而數組是容器的子項以整數索引。 以下擴展方法可以完成此任務:

public interface IJTokenWorker
{
    bool ProcessToken<TConvertible>(JContainer parent, TConvertible index, JToken current, int depth) where TConvertible : IConvertible;
}

public static partial class JsonExtensions
{
    public static void WalkTokens(this JToken root, IJTokenWorker worker, bool includeSelf = false)
    {
        if (worker == null)
            throw new ArgumentNullException();
        DoWalkTokens<int>(null, -1, root, worker, 0, includeSelf);
    }

    static void DoWalkTokens<TConvertible>(JContainer parent, TConvertible index, JToken current, IJTokenWorker worker, int depth, bool includeSelf) where TConvertible : IConvertible
    {
        if (current == null)
            return;
        if (includeSelf)
        {
            if (!worker.ProcessToken(parent, index, current, depth))
                return;
        }
        var currentAsContainer = current as JContainer;
        if (currentAsContainer != null)
        {
            IList<JToken> currentAsList = currentAsContainer; // JContainer implements IList<JToken> explicitly
            for (int i = 0; i < currentAsList.Count; i++)
            {
                var child = currentAsList[i];
                if (child is JProperty)
                {
                    DoWalkTokens(currentAsContainer, ((JProperty)child).Name, ((JProperty)child).Value, worker, depth+1, true);
                }
                else
                {
                    DoWalkTokens(currentAsContainer, i, child, worker, depth+1, true);
                }
            }
        }
    }
}

然后,您的Convert()方法現在變為:

class JTokenPrinter : IJTokenWorker
{
    public bool ProcessToken<TConvertible>(JContainer parent, TConvertible index, JToken current, int depth) where TConvertible : IConvertible
    {
        var spacer = new String('\t', depth);
        string name;
        string val;

        if (parent != null && index is int)
            name = string.Format("[{0}]", index);
        else if (parent != null && index != null)
            name = index.ToString();
        else 
            name = "";

        if (current is JValue)
            val = ((JValue)current).ToString();
        else if (current is JConstructor)
            val = "new " + ((JConstructor)current).Name;
        else
            val = "-";

        Console.WriteLine(string.Format("{0}{1}   -> {2}", spacer, name, val));
        return true;
    }
}

public static void Convert(string json)
{
    var root = JsonConvert.DeserializeObject<JToken>(json);
    root.WalkTokens(new JTokenPrinter());
}

演示小提琴#2 在這里 ,輸出:

allOf   -> -
    [0]   -> -
        field   -> type
        equals   -> Microsoft.KeyVault/vaults
    [1]   -> -
        anyOf   -> -
            [0]   -> -
                field   -> Microsoft.KeyVault/vaults/networkAcls.virtualNetworkRules[*].id
                exists   -> false
            [1]   -> -
                field   -> Microsoft.KeyVault/vaults/networkAcls.virtualNetworkRules[*].id
                notLike   -> *
            [2]   -> -
                field   -> Microsoft.KeyVault/vaults/networkAcls.defaultAction
                equals   -> Allow

有關:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM