如何从 Cloud Workflows 实例返回特定项目?

问题描述 投票:0回答:1

我在从 JSON 响应实例中获取数据时遇到问题。我正在使用 Cloud Workflows 来获取有关虚拟机当前状态的信息。我正在使用

.get
函数返回这个高度结构化的长 JSON,例如
launchResult
返回为:

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

我可以通过

${launchResult.status}
返回例如“某些状态”, 甚至
key1
,如
{launchResult.items[0].key}

问题是:我怎样才能像

launchResult.items["key" == "key1"].property1
那样做某事?我的意思是我想根据密钥从项目中返回
property1

json yaml conditional-statements google-workflows
1个回答
2
投票

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

  • 迭代列表中的元素,直到找到具有您要查找的属性的元素。

这是我制作的示例代码,用于展示如何在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

另请参阅:

© www.soinside.com 2019 - 2024. All rights reserved.