借助JOLT转换来整平整个json文档

时间:2017-09-12 16:16:48

标签: json jolt

我在json下面:

     {
    "deveui": "1000",
    "vars": [
        { "name": "CfgNo",
           "value":"255" },
        {
            "name":"Status","value":{
                "lampS": "unknown(0xff)",
                "lampL": "255"
            }
        },
        { "name" : "Volt", "value": "255" },
        {
            "name" : "gps", "value": {
                "lat": "12.93",
                "lon": "77.69"
             }
        },
        {"name" : "status", "value":"up"},
        {"name" : "last_status_change","value": 1503 }
    ]
} 

预期输出为:

{[{  "deveui": "1000",
  "CfgNo": "255",
  "lampS": "unknown(0xff)",
  "lampL": "255",
  "Volt": "255",
  "lat": "12.93",
  "lon": "77.69",
  "status": "up",
  "last_status_change": 1503 
}]}

是否可以转换为预期的输出格式。如果是这样,请帮我设计规格。

1 个答案:

答案 0 :(得分:0)

它看起来应该很简单,但如果是地图或标量,Shift不能以不同的方式匹配。在这种情况下,"值"在你的输入中有时是一个标量,有时候是一个嵌套的地图。

如果您知道"名称"这将是多重价值,然后Jolt可以提供帮助。

规格

[
  {
    // Shift can't vary its behavior between 
    //  the "value" key in the input being a 
    //  scalar or a map.
    // Thus the only way to do the desired flattening
    //  is if we know the names that will 
    //  be multi-valued.
    "operation": "shift",
    "spec": {
      // pass deveui thru
      "deveui": "deveui",
      "vars": {
        "*": { // array index of vars[]
          "name": {
            // match value of name Status or gps
            "Status|gps": {
              // We know these entries have "value" that is map.
              // For these, go back up the tree, 3 levels (0,1,2)
              // and come back down to the "value" entry.
              "@(2,value)": {
                // for each key in the value, pass it thru
                // to the output.
                "*": "&"
              }
            },
            "*": {
              // for all other values of "name" that are not
              //  Status or gps, just go back up the tree
              //  and grab the scalear "value" and write it
              //  to the output at the matched value of name.
              "@(2,value)": "&1"
            }
          }
        }
      }
    }
  }
]