2017-08-04 74 views
0

我是一个颠簸新手。 我有以下问题,我有一个JSON文档结构,其中可能会有所不同,基于type属性。看我下面的例子。 { "recipientId": "xxx", "messages": [ { "type": "text", "text": "hi there!" }, { "type": "image", "url": "http://example.com/image.jpg", "preview": "http://example.com/thumbnail.jpg" } ] } 改造后,我想收到以下输出: { "messages" : [ { "text" : "hi there!", "type" : "text" }, { "type" : "image", "url" : "http://example.com/image.jpg", "preview": "http://example.com/thumbnail.jpg" } ], "to" : "xxx" } 基于其中一个属性值的JOLT子树验证

这里是我想出了规范: [ { "operation": "shift", "spec": { "recipientId": "to", "messages": { "*": { "type": "messages[&1].type", "text": "messages[&1].text", "url": "messages[&1].url", "preview": "messages[&1].previewImageUrl" } } } } ]

这种方法的问题是,如果我有"type": "text",如果我也会抛出"preview"属性值,因此text不应该具有"preview"属性集。 因此,我希望jolt基于“type”属性的值忽略某些属性或避免转换此类有效内容。

有没有办法在JOLT中做这样的“验证”?我看到的另一个选项是用Jackson类型层次结构验证它。

回答

0

你可以做的是匹配“type”的值,然后跳回树中的一些,并将消息处理为“文本”类型或“图像”类型。

输入

​​3210

规格

[ 
    { 
    "operation": "shift", 
    "spec": { 
     "recipientId": "to", 
     "messages": { 
     "*": { // the array index of the messages array, referenced below 
       // as [&2] or [&4] depending how far down they have gone 
      "type": { 
      // always pass the value of type thru 
      "@": "messages[&2].type", 

      "text": { 
       // if the value of type was "text", then 
       // go back up the tree 3 levels (0,1,2) 
       // and process the whole message as a "text" type 
       "@2": { 
       "text": "messages[&4].text" 
       } 
      }, 
      "image": { 
       "@2": { 
       // if the value of type was "image", then 
       // go back up the tree 3 levels (0,1,2) 
       // and process the whole message as a "image" type 
       "url": "messages[&4].url", 
       "preview": "messages[&4].previewImageUrl" 
       } 
      } 
      } 
     } 
     } 
    } 
    } 
] 
+0

非常感谢您的回复,非常感谢! 我已经试过你的规格。 它允许跳过不属于特定消息类型的属性。 但它不验证是否存在对特定消息类型至关重要的所有属性。例如,如果“类型”设置为“文本”,我会希望冲突转换失败,如果“文本”属性不存在于消息中。事实上,即使没有重要的密钥,颠簸也会转变。 –

+0

如果强制性关键字不在树中,是否有办法强制jolt失败转换? –

+0

不,jolt是专门设计的,不会失败。对于这样的事情(这个或那个关键是强制性的)应该使用不同的工具,比如某种Json Schema。 –

相关问题