简体   繁体   English

使用 jolt 转换从 json 中提取值

[英]Extracting value from json using jolt transformation

I have a json object:我有一个 json 对象:

{

  "Data" : "{field1: [x,y],
               field2: z}",
}

Output json:输出json:

{

  "field3": "z"

}
[
  {
    "operation": "shift",
    "spec": {
      "Data": {
        "*field2:*}*": {
          "$(0,2)": "field3"
        }
      }
    }
  }
]

Here the value of "Data" is a complete string not a json, hence I have to break it into wildcards and now the 2nd '*' in the spec gives me the value "z".这里“Data”的值是一个完整的字符串而不是 json,因此我必须将它分成通配符,现在规范中的第二个“*”给了我值“z”。 Is there any better approach to do the same such that say a new field comes before or after field2 then I don't have to modify this regex.有没有更好的方法来做同样的事情,比如在 field2 之前或之后有一个新字段,那么我不必修改这个正则表达式。

Firstly this doesn't feel like problem to be solved in JOLT, and instead the Data should be extracted and serialized to JSON.首先,这不像是 JOLT 中要解决的问题,而是应该提取Data并将其序列化为 JSON。

That said i've managed to get something to work, explanation inline:那就是说我已经设法使某些东西起作用,内联解释:

[
  //Remove {
  {
    "operation": "shift",
    "spec": {
      "Data": {
        "{*": {
          "$(0,1)": "Data"
        }
      }
    }
  },
  //Remove }
  {
    "operation": "shift",
    "spec": {
      "Data": {
        "*}": {
          "$(0,1)": "Data"
        }
      }
    }
  },
  // Split by ,
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "Data": "=split(',', @(2,Data))"
    }
  },
  // Trim
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "Data": {
        "*": "=trim"
      }
    }
  },
  // Select field2
  {
    "operation": "shift",
    "spec": {
      "Data": {
        "*": {
          "field2:*": {
            "$(0,1)": "field3"
          }
        }
      }
    }
  },
  // Trim again
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": "=trim"
    }
  }
]


Tested against:针对:

{
  "Data": "{field1: [x,y], field2: z}"
}

and

{
  "Data": "{ field2: z, field1: [x,y]}"
}

and

{
  "Data": "{field1: [x,y], field2: z, field3: [x,y]}"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM