2

我有从 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、 as返回“某种状态” {launchResult.items[0].key}

问题是:我该怎么做launchResult.items["key" == "key1"].property1?我的意思是我想property1根据密钥从项目中返回。

4

1 回答 1

1

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

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

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

也可以看看:

于 2021-12-02T22:09:00.223 回答