如何将JSON对象名称转换为元素名称?另外,要删除嵌套对象吗?

时间:2019-01-06 00:58:21

标签: json mule-studio dataweave

使用Dataweave,我正在尝试对此进行转换:

{
    "ConcurrentAsyncGetReportInstances": {
        "Max": 200,
        "Remaining": 200
    },
    "ConcurrentSyncReportRuns": {
        "Max": 20,
        "Remaining": 20
    },
    "DailyAnalyticsDataflowJobExecutions": {
        "Max": 50,
        "Remaining": 50
    },
    "DailyApiRequests": {
        "Max": 6175000,
        "Remaining": 6174972,
        "Ant Migration Tool": {
            "Max": 0,
            "Remaining": 0
        },
        "CLM_service_api": {
            "Max": 0,
            "Remaining": 0
        },
        "CRM_service_api": {
            "Max": 0,
            "Remaining": 0
        }
    },
    "DailyAsyncApexExecutions": {
        "Max": 325000,
        "Remaining": 324902
 }

对此:

[
{
    "name":"ConcurrentAsyncGetReportInstances",
    "max":200,
    "remaining":200 
},
{
    "name":"ConcurrentSyncReportRuns",
    "max":"20",
    "remaining":"20"    
},
{
    "name":"DailyAnalyticsDataflowJobExecutions",
    "max":50,
    "remaining":50  
},
{
    "name":"DailyApiRequests",
    "max":6175000,
    "remaining":6174972 
},
{
    "name":"DailyAsyncApexExecutions",
    "max":325000,
    "remaining":324902  
}
]

也-请注意,我不需要像DailyApiRequests中那样的任何嵌套值

我尝试过地图功能,但不确定如何正确使用。我看到的所有示例似乎都没有显示这种情况。

3 个答案:

答案 0 :(得分:2)

使用DataWeave

COUNTIFS

答案 1 :(得分:0)

如果您使用的是 JavaScript ,则可以使用包lodash并使用其map函数:

代码

const _ = require('lodash')

const obj = ... // your object above
const res = _.map(obj, (v, k) => ({
  name: k, 
  max: v.Max, 
  remaining: v.Remaining
}))

console.log(res)

输出

enter image description here

查看lodash文档here

您可以做的另一件事是手动遍历对象属性并自己制作地图,但我认为您最终将重新发明轮子并正好做lodash的工作;)因此,尝试一下。顺便说一句,该软件包非常了不起,非常有用。

答案 2 :(得分:0)

与Josué相似,但没有引入不必要的依赖关系。

const obj = {} // your object above
const res = Object.entries(obj).map( [k, v] => ({
  name: k, 
  ...v
}))

另一个例子,但有一个简单的循环:

const obj = {}; // your object above
const res = []; // New object
for(const [k, v] of Object.entries(obj)) {
  res.push({
    ...v,
    name: k
  });
}

将在使用十年的浏览器中运行的示例:

var obj = {}; // your object above
var res = []; // New object
for(var key in obj) {
  if (!obj.hasOwnProperty(key)) continue;
  res.push({
    name: k, 
    max: obj[k].Max, 
    remaining: obj[k].Remaining
  });
}