如何 return Cloud Workflows 实例中的特定项目?

How to return specific item from Cloud Workflows instance?

我无法从 JSON 响应实例中获取数据。我正在使用 Cloud Workflows 获取有关我的虚拟机当前状态的信息。我正在使用 return 这么长 JSON 的 .get 函数,它是高度结构化的,例如launchResult 被 return 编辑为:

{
   "name":"some name",
   "status":"some status",
   "items":[
      {
         "key":"key1",
         "property1":"xxxx",
         "property2":"ccvdvdvd"
      },
      {
         "key":"key2",
         "property1":"xxxrerex",
         "property2":"ccvdveedvd"
      }
   ],
   "kind":"some kind"
}

我可以 return 例如“某些状态”,通过 ${launchResult.status}, 甚至 key1,如 {launchResult.items[0].key}.

问题是:我怎样才能像launchResult.items["key" == "key1"].property1那样做某事?我的意思是我想根据键 return 来自项目的 property1

要根据地图列表中另一个 属性 的值从地图列表中的一个项目中获取 属性,我建议如下:

  • 遍历列表的元素,直到找到具有您要查找的 属性 的元素。

这是我为展示 how to use iterations along with conditionals in Cloud Workflows 实现此目的而制作的示例代码:

main:
  params: []
  steps:
  - define:
      assign:
        # Incremental variable set to zero
        - i: 0
        # Value to look up in list
        - cond: "key2"
        # A variable that contains a sample data as the JSON
        # showed in the question
        - test: 
            name: some name
            status: some status
            items:
            - key: "key1"
              property1: xxxx
              property2: ccvdvdvd
            - key: "key2"
              property1: xxxrerex
              property2: ccvdveedvd
            - key: "key3"
              property1: xxex
              property2: ccvdvffdvd
            kind: some kind
  - lookupInItems:
      switch:
        # Here we're looking for the element over the list test.items until the condition is met 
        # or the list ends
        - condition: ${i < len(test.items) and test.items[i].key!=cond}
        # If the condition is not met, keep iterating using iterate step
          next: iterate
      # If the element is found or the list ends, jumps to the read step
      next: read
  - iterate:
      assign: 
      # Increment the increment variable i
        - i: ${i+1}
      next: lookupInItems
  # If the iteration ends, check for the value
  - read:
      switch:
        # Check if the value was found
        # if this check is not made, an out of index error will occur when trying to show
        # the property of a value does not exists
        - condition: ${i < len(test.items)}
          next: found
      next: notfound
  # Print a message on the sys.log either the value was found or not
  - notfound:
      call: sys.log
      args:
        text: ${"Value " + cond + " not found in list"}
        severity: "WARNING"
      next: end
  - found:
      call: sys.log
      args:
        text: ${test.items[i].property1}
        severity: "INFO"
      next: end

另请参阅: