Обработка нулевых значений в приложении логики с таблицей JSON и создание объекта - PullRequest
0 голосов
/ 01 ноября 2019

Оповещение Azure запускает приложение логики для вывода, например, входных данных JSON схемы общего оповещения Microsoft Teams в приложение логики.

В таблице JSON есть столбцы и строки

Составлять достаточно простообъект с фиксированным значением в массиве, см. пример ниже.

Однако это не удается, когда любое значение равно нулю. Что подводит меня к сути. Я должен быть в состоянии динамически создать таблицу с доступной информацией. Я чувствую себя ограниченным в том, что я могу сделать с приложением логики. С PowerShell я, вероятно, решил бы это с помощью хеш-таблицы.

Я пытался перебирать строки и столбцы и добавлять в массив. Однако получение данных происходит повсеместно, что логично.

Полагаю, мне нужно как-то перебирать и компоновать и возражать, но потом я просто перезаписываю объект с каждой итерацией

Пример работы сфиксированные значения

Variable Math
item()[2]

Variable Number
if(contains('56789', substring(string(variables('math')),4,1)),substring(string(add(variables('math'),0.01)),0,4),substring(string(variables('math')),0,4))

Compose Object
{

"AggregatedValue": @{variables('Number')},

"Computer": "@{item()[0]}    ",

"TimeGenerated": "@{item()[1]}"

}

Я получаю следующую таблицу для работы с


[
  {
    "name": "PrimaryResult",
    "columns": [
      {
        "name": "Computer",
        "type": "string"
      },
      {
        "name": "TimeGenerated",
        "type": "datetime"
      },
      {
        "name": "AggregatedValue",
        "type": "real"
      }
    ],
    "rows": [
      [
        "server.example.org",
        "2019-10-30T08:44:48Z",
        2.409970182797006
      ]
    ]
  }
]

JSON-схемой

{
  "properties": {
    "data": {
      "properties": {
        "alertContext": {
          "properties": {
            "AffectedConfigurationItems": {
              "items": {
                "type": "string"
              },
              "type": "array"
            },
            "AlertType": {
              "type": "string"
            },
            "IncludedSearchResults": {
              "type": "string"
            },
            "LinkToSearchResults": {
              "type": "string"
            },
            "Operator": {
              "type": "string"
            },
            "ResultCount": {
              "type": "integer"
            },
            "SearchIntervalDurationMin": {
              "type": "string"
            },
            "SearchIntervalEndtimeUtc": {
              "type": "string"
            },
            "SearchIntervalInMinutes": {
              "type": "string"
            },
            "SearchIntervalStartTimeUtc": {
              "type": "string"
            },
            "SearchQuery": {
              "type": "string"
            },
            "SearchResults": {
              "properties": {
                "dataSources": {
                  "items": {
                    "properties": {
                      "resourceId": {
                        "type": "string"
                      },
                      "tables": {
                        "items": {
                          "type": "string"
                        },
                        "type": "array"
                      }
                    },
                    "required": [
                      "resourceId",
                      "tables"
                    ],
                    "type": "object"
                  },
                  "type": "array"
                },
                "tables": {
                  "items": {
                    "properties": {
                      "columns": {
                        "items": {
                          "properties": {
                            "name": {
                              "type": "string"
                            },
                            "type": {
                              "type": "string"
                            }
                          },
                          "required": [
                            "name",
                            "type"
                          ],
                          "type": "object"
                        },
                        "type": "array"
                      },
                      "name": {
                        "type": "string"
                      },
                      "rows": {
                        "items": {
                          "type": "array"
                        },
                        "type": "array"
                      }
                    },
                    "required": [
                      "name",
                      "columns",
                      "rows"
                    ],
                    "type": "object"
                  },
                  "type": "array"
                }
              },
              "type": "object"
            },
            "SeverityDescription": {
              "type": "string"
            },
            "Threshold": {
              "type": "integer"
            },
            "WorkspaceId": {
              "type": "string"
            }
          },
          "type": "object"
        },
        "essentials": {
          "properties": {
            "alertContextVersion": {
              "type": "string"
            },
            "alertId": {
              "type": "string"
            },
            "alertRule": {
              "type": "string"
            },
            "alertTargetIDs": {
              "items": {
                "type": "string"
              },
              "type": "array"
            },
            "description": {
              "type": "string"
            },
            "essentialsVersion": {
              "type": "string"
            },
            "firedDateTime": {
              "type": "string"
            },
            "monitorCondition": {
              "type": "string"
            },
            "monitoringService": {
              "type": "string"
            },
            "originAlertId": {
              "type": "string"
            },
            "severity": {
              "type": "string"
            },
            "signalType": {
              "type": "string"
            }
          },
          "type": "object"
        }
      },
      "type": "object"
    },
    "schemaId": {
      "type": "string"
    }
  },
  "type": "object"
}

Ожидаемый вывод

All values not null
computer        Timegenerated       AggregatedValue
server.example.org  2019-10-30T08:44:48Z    2.41
Two values null
computer        Timegenerated       AggregatedValue
server.example.org

1 Ответ

0 голосов
/ 04 ноября 2019

Если вы хотите использовать приложение логики для обработки этих данных, вам нужно добавить некоторые действия для обработки ошибок. Я использую Parse JSON для имитации получения данных таблицы.

Я инициализирую переменную Timegenerated и задаю для нее значение в таблице, а также пробел, пока последнее действие не удалось.

enter image description here

enter image description here

И затем инициализируйте math так же, как Timegenerated. Еще один шаг - инициировать переменную Number с помощью if(contains('56789', substring(string(variables('math')),4,1)),substring(string(add(float(variables('math')),0.01)),0,4),substring(string(variables('math')),0,4)) и установить ее запуск после пропуска последнего действия.

enter image description here

enter image description here

Наконец, выполните действие compose: одно с переменной math запускается после пропуска переменной init Number, а другое с переменной Number.

enter image description here

enter image description here

И если вы считаете, что это слишком громоздко, вы можете использовать функцию Azure для обработки этих данных. функция Azure поддерживает PowerShell , также вы можете вызвать функцию Azure в приложении логики для обработки данных вашей таблицы в функцию, в функции PowerShell обработать их, затем вернуть их в приложение логики, а затемвы сможете получить нужные данные в приложении логики.

...