如何从json对象中删除所有null和空字符串值? [英] How do I remove all null and empty string values from a json object?

查看:93
本文介绍了如何从json对象中删除所有null和空字符串值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我如何从json对象中删除所有null和空字符串值吗?我在删除密钥时收到错误。



这是我到目前为止所做的,但它无法正常工作:

  $。each(sjonObj,function(key,value){
if(value ==|| value == null){
删除sjonObj.key;
}
});

  var sjonObj = {executionMode:SEQUENTIAL ,coreTEEVersion:3.3.1.4_RC8,testSuiteId:yyy,testSuiteFormatVersion:1.0.0.0,testStatus:IDLE,reportPath:,startTime: 0,durationBetweenTestCases:20,endTime:0,lastExecutedTestCaseId:0,repeatCount:0,retryCount:0,fixedTimeSyncSupported:false,totalRepeatCount:0,totalRetryCount:0, summaryReportRequired:true,postConditionExecution:ON_SUCCESS,testCaseList:[{executionMode:SEQUENTIAL,commandList:[],testCaseList:[],testStatus:IDLE ,boundTimeDurationForExecution:0,startTime:0,endTime:0,label:null,repeatCount:0,retryCount:0,totalRepea tCount:0,totalRetryCount:0,testCaseId:a,summaryReportRequired:false,postConditionExecution:ON_SUCCESS},{executionMode:SEQUENTIAL,commandList:[ ],testCaseList:[{executionMode:SEQUENTIAL,commandList:[{commandParameters:{serverAddress:www.ggp.com,echoRequestCount:,sendPacketSize: ,interval:,ttl:,addFullDataInReport:True,maxRTT:,failOnTargetHostUnreachable:True,failOnTargetHostUnreachableCount:,initialDelay :,commandTimeout:,testDuration:},commandName:Ping,testStatus:IDLE,label:,reportFileName:tc_2-tc _1-cmd_1_Ping,endTime:0,startTime:0,repeatCount:0,retryCount:0,totalRepeatCount:0,totalRetryCount:0,postConditionExecution:ON_SUCCESS, detailReportRequired:true,summaryReportRequired:true}],testCaseList:[],testStatus:IDLE,boundTimeDurationForExecution:0,startTime:0,endTime:0, label:null,repeatCount:0,retryCount:0,totalRepeatCount:0,totalRetryCount:0,testCaseId:dd,summaryReportRequired:false,postConditionExecution: ON_SUCCESS}],testStatus:IDLE,boundTimeDurationForExecution:0,startTime:0,endTime:0,label:null,repeatCount:0,retryCount:0,totalRepeatCount:0,totalRetryCount:0,testCaseId:b,summaryReportRequired:false,postConditionExecution:ON_SUCCESS}]}; $。each(sjonObj,function(key,value) ){if(value ==|| value == null){delete sjonObj.key; };); console.log(sjonObj);  

 < ; script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>  

解决方案

您要删除 sjonObj.key ,字面意思。您需要使用数组访问表示法:

  delete sjonObj [key]; 

然而,这也会删除值等于0的地方,因为你没有使用严格的比较。改为使用 ===

  $。each(sjonObj,function (键,值){
if(value ===|| value === null){
delete sjonObj [key];
}
});

但是,这只会使对象浅浅。要做得很深,你可以使用递归:

 (函数过滤器(obj){
$ .each(obj) ,function(key,value){
if(value ===|| value === null){
delete obj [key];
} else if(Object.prototype) .toString.call(value)==='[object Object]'){
filter(value);
} else if($ .isArray(value)){
$ .each (value,function(k,v){filter(v);});
}
});
})(sjonObj);

  var sjonObj = {executionMode:SEQUENTIAL,coreTEEVersion:3.3.1.4_RC8,testSuiteId:yyy,testSuiteFormatVersion:1.0.0.0,testStatus: IDLE,reportPath:,startTime:0,durationBetweenTestCases:20,endTime:0,lastExecutedTestCaseId:0,repeatCount:0,retryCount:0,fixedTimeSyncSupported: false,totalRepeatCount:0,totalRetryCount:0,summaryReportRequired:true,postConditionExecution:ON_SUCCESS,testCaseList:[{executionMode:SEQUENTIAL,commandList:[] ,testCaseList:[],testStatus:IDLE,boundTimeDurationForExecution:0,startTime:0,endTime:0,label:null,repeatCount: 0,retryCount:0,totalRepeatCount:0,totalRetryCount:0,testCaseId:a,summaryReportRequired:false,postConditionExecution:ON_SUCCESS},{executionMode: SEQUENTIAL,commandList:[],testCaseList:[{executionMode:SEQUENTIAL,commandList:[{commandParameters:{serverAddress:www.ggp.com,echoRequestCount :,sendPacketSize:,interval:,ttl:,addFullDataInReport:True,maxRTT:,failOnTargetHostUnreachable:True, failOnTargetHostUnreachableCount:,initialDelay:,commandTimeout:,testDuration:},commandName:Ping,testStatus:IDLE,label: ,reportFileName:tc_2-tc_1-cmd_1_Ping,endTime:0,startTime:0,repeatCount:0,retryCount:0,totalRepeatCount:0,totalRetryCount:0, postConditionExecution:ON_SUCCESS,detailReportRequired:true,summaryReportRequired:true}],testCaseList:[],testStatus:IDLE,boundTimeDurationForExecution:0,startTime: 0,endTime:0,label:null,repeatCount:0,retryCount:0,totalRepeatCount:0,totalRetryCount:0,testCaseId:dd,summaryReportRequired: false,postConditionExecution:ON_SUCCESS}],testStatus:IDLE,boundTimeDurationForExecution:0,startTime:0,endTime:0,label:null,r epeatCount:0,retryCount:0,totalRepeatCount:0,totalRetryCount:0,testCaseId:b,summaryReportRequired:false,postConditionExecution:ON_SUCCESS}]}; (函数filter(obj){$ .each(obj,function(key,value){if(value ===|| value === null){delete obj [key]; } else if(Object.prototype.toString.call(value)==='[object Object]'){filter(value); } else if(Array.isArray(value)){value.forEach(function(el){filter(el);}); }});}}(sjonObj); console.log(sjonObj) 

 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>  






请注意,如果您愿意使用像lodash / underscore.js这样的库,你可以使用 _。选择。但是,您仍然需要使用递归来深度过滤,因为两个库都没有提供深度过滤功能。

  sjonObj =(function filter(obj){
var filtered = _.pick(obj,function(v){return v!==''&& v!== null;});
return _。 cloneDeep(filtered,function(v){return v!== filtered&& _.isPlainObject(v)?filter(v):undefined;});
})(sjonObj);

此变体具有保持原始对象不被修改的附加优势,但它确实创建了一个全新的副本,如果你不需要原始对象,效率会降低。



  var sjonObj = {executionMode:SEQUENTIAL,coreTEEVersion:3.3.1.4_RC8,testSuiteId:yyy,testSuiteFormatVersion:1.0.0.0,testStatus :IDLE,reportPath:,startTime:0,durationBetweenTestCases:20,endTime:0,lastExecutedTestCaseId:0,repeatCount:0,retryCount:0,fixedTimeSyncSupported :false,totalRepeatCount:0,totalRetryCount:0,summaryReportRequired:true,postConditionExecution:ON_SUCCESS,testCaseList:[{executionMode:SEQUENTIAL,commandLi st:[],testCaseList:[],testStatus:IDLE,boundTimeDurationForExecution:0,startTime:0,endTime:0,label:null,repeatCount:0 ,retryCount:0,totalRepeatCount:0,totalRetryCount:0,testCaseId:a,summaryReportRequired:false,postConditionExecution:ON_SUCCESS},{executionMode: SEQUENTIAL,commandList:[],testCaseList:[{executionMode:SEQUENTIAL,commandList:[{commandParameters:{serverAddress:www.ggp.com,echoRequestCount :,sendPacketSize:,interval:,ttl:,addFullDataInReport:True,maxRTT:,failOnTargetHostUnreachable:True,failOnTargetHostUnreachableCount :, initialDelay:,commandTimeout:,testDuration:},commandName:Ping,testStatus:IDLE,label:,reportFileName: tc_2-tc_1-cmd_1_Ping,endTime:0,startTime:0,repeatCount:0,retryCount:0,totalRepeatCount:0,totalRetryCount:0,postConditionExecution:ON_SUCCESS ,detailReportRequired:true,summaryReportRequired:true}],testCaseList:[],testStatus:IDLE,boundTimeDurationForExecution:0,startTime:0,endTime: 0,label:null,repeatCount:0,retryCount:0,totalRepeatCount:0,totalRetryCount:0,testCaseId:dd,summaryReportRequired: false,postConditionExecution:ON_SUCCESS}],testStatus:IDLE,boundTimeDurationForExecution:0,startTime:0,endTime:0,label:null,repeatCount: 0,retryCount:0,totalRepeatCount:0,totalRetryCount:0,testCaseId:b,summaryReportRequired:false,postConditionExecution:ON_SUCCESS}]}; sjonObj =(函数过滤器(obj){var filtered = _.pick(obj,function(v){return v!==''&& v!== null; }); return _.cloneDeep(filtered,function(v){return v!== filtered&& _.isPlainObject(v)?filter(v):undefined;});}}(sjonObj); console.log(sjonObj );  

 < script src =// cdnjs。 cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js\"></script>  


Can you please tell me how to remove all null and empty string values from a json object? I am getting an error while deleting the key.

This is what I have so far, but it doesn't work properly:

$.each(sjonObj, function(key, value) {
    if(value == "" || value == null) {
        delete sjonObj.key;
    }
});

var sjonObj= {
  "executionMode": "SEQUENTIAL",
  "coreTEEVersion": "3.3.1.4_RC8",
  "testSuiteId": "yyy",
  "testSuiteFormatVersion": "1.0.0.0",
  "testStatus": "IDLE",
  "reportPath": "",
  "startTime": 0,
  "durationBetweenTestCases": 20,
  "endTime": 0,
  "lastExecutedTestCaseId": 0,
  "repeatCount": 0,
  "retryCount": 0,
  "fixedTimeSyncSupported": false,
  "totalRepeatCount": 0,
  "totalRetryCount": 0,
  "summaryReportRequired": "true",
  "postConditionExecution": "ON_SUCCESS",
  "testCaseList": [
    {
      "executionMode": "SEQUENTIAL",
      "commandList": [
        
      ],
      "testCaseList": [
        
      ],
      "testStatus": "IDLE",
      "boundTimeDurationForExecution": 0,
      "startTime": 0,
      "endTime": 0,
      "label": null,
      "repeatCount": 0,
      "retryCount": 0,
      "totalRepeatCount": 0,
      "totalRetryCount": 0,
      "testCaseId": "a",
      "summaryReportRequired": "false",
      "postConditionExecution": "ON_SUCCESS"
    },
    {
      "executionMode": "SEQUENTIAL",
      "commandList": [
        
      ],
      "testCaseList": [
        {
          "executionMode": "SEQUENTIAL",
          "commandList": [
            {
              "commandParameters": {
                "serverAddress": "www.ggp.com",
                "echoRequestCount": "",
                "sendPacketSize": "",
                "interval": "",
                "ttl": "",
                "addFullDataInReport": "True",
                "maxRTT": "",
                "failOnTargetHostUnreachable": "True",
                "failOnTargetHostUnreachableCount": "",
                "initialDelay": "",
                "commandTimeout": "",
                "testDuration": ""
              },
              "commandName": "Ping",
              "testStatus": "IDLE",
              "label": "",
              "reportFileName": "tc_2-tc_1-cmd_1_Ping",
              "endTime": 0,
              "startTime": 0,
              "repeatCount": 0,
              "retryCount": 0,
              "totalRepeatCount": 0,
              "totalRetryCount": 0,
              "postConditionExecution": "ON_SUCCESS",
              "detailReportRequired": "true",
              "summaryReportRequired": "true"
            }
          ],
          "testCaseList": [
            
          ],
          "testStatus": "IDLE",
          "boundTimeDurationForExecution": 0,
          "startTime": 0,
          "endTime": 0,
          "label": null,
          "repeatCount": 0,
          "retryCount": 0,
          "totalRepeatCount": 0,
          "totalRetryCount": 0,
          "testCaseId": "dd",
          "summaryReportRequired": "false",
          "postConditionExecution": "ON_SUCCESS"
        }
      ],
      "testStatus": "IDLE",
      "boundTimeDurationForExecution": 0,
      "startTime": 0,
      "endTime": 0,
      "label": null,
      "repeatCount": 0,
      "retryCount": 0,
      "totalRepeatCount": 0,
      "totalRetryCount": 0,
      "testCaseId": "b",
      "summaryReportRequired": "false",
      "postConditionExecution": "ON_SUCCESS"
    }
  ]
};

$.each(sjonObj, function(key, value) {
    if(value == "" || value == null) {
        delete sjonObj.key;
    }
});

console.log(sjonObj);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

解决方案

You're deleting sjonObj.key, literally. You need to use array access notation:

delete sjonObj[key];

However, that will also delete where value is equal to 0, since you're not using strict comparison. Use === instead:

$.each(sjonObj, function(key, value){
    if (value === "" || value === null){
        delete sjonObj[key];
    }
});

However, this will only walk the object shallowly. To do it deeply, you can use recursion:

(function filter(obj) {
    $.each(obj, function(key, value){
        if (value === "" || value === null){
            delete obj[key];
        } else if (Object.prototype.toString.call(value) === '[object Object]') {
            filter(value);
        } else if ($.isArray(value)) {
            $.each(value, function (k,v) { filter(v); });
        }
    });
})(sjonObj);

var sjonObj = {
  "executionMode": "SEQUENTIAL",
  "coreTEEVersion": "3.3.1.4_RC8",
  "testSuiteId": "yyy",
  "testSuiteFormatVersion": "1.0.0.0",
  "testStatus": "IDLE",
  "reportPath": "",
  "startTime": 0,
  "durationBetweenTestCases": 20,
  "endTime": 0,
  "lastExecutedTestCaseId": 0,
  "repeatCount": 0,
  "retryCount": 0,
  "fixedTimeSyncSupported": false,
  "totalRepeatCount": 0,
  "totalRetryCount": 0,
  "summaryReportRequired": "true",
  "postConditionExecution": "ON_SUCCESS",
  "testCaseList": [
    {
      "executionMode": "SEQUENTIAL",
      "commandList": [
        
      ],
      "testCaseList": [
        
      ],
      "testStatus": "IDLE",
      "boundTimeDurationForExecution": 0,
      "startTime": 0,
      "endTime": 0,
      "label": null,
      "repeatCount": 0,
      "retryCount": 0,
      "totalRepeatCount": 0,
      "totalRetryCount": 0,
      "testCaseId": "a",
      "summaryReportRequired": "false",
      "postConditionExecution": "ON_SUCCESS"
    },
    {
      "executionMode": "SEQUENTIAL",
      "commandList": [
        
      ],
      "testCaseList": [
        {
          "executionMode": "SEQUENTIAL",
          "commandList": [
            {
              "commandParameters": {
                "serverAddress": "www.ggp.com",
                "echoRequestCount": "",
                "sendPacketSize": "",
                "interval": "",
                "ttl": "",
                "addFullDataInReport": "True",
                "maxRTT": "",
                "failOnTargetHostUnreachable": "True",
                "failOnTargetHostUnreachableCount": "",
                "initialDelay": "",
                "commandTimeout": "",
                "testDuration": ""
              },
              "commandName": "Ping",
              "testStatus": "IDLE",
              "label": "",
              "reportFileName": "tc_2-tc_1-cmd_1_Ping",
              "endTime": 0,
              "startTime": 0,
              "repeatCount": 0,
              "retryCount": 0,
              "totalRepeatCount": 0,
              "totalRetryCount": 0,
              "postConditionExecution": "ON_SUCCESS",
              "detailReportRequired": "true",
              "summaryReportRequired": "true"
            }
          ],
          "testCaseList": [
            
          ],
          "testStatus": "IDLE",
          "boundTimeDurationForExecution": 0,
          "startTime": 0,
          "endTime": 0,
          "label": null,
          "repeatCount": 0,
          "retryCount": 0,
          "totalRepeatCount": 0,
          "totalRetryCount": 0,
          "testCaseId": "dd",
          "summaryReportRequired": "false",
          "postConditionExecution": "ON_SUCCESS"
        }
      ],
      "testStatus": "IDLE",
      "boundTimeDurationForExecution": 0,
      "startTime": 0,
      "endTime": 0,
      "label": null,
      "repeatCount": 0,
      "retryCount": 0,
      "totalRepeatCount": 0,
      "totalRetryCount": 0,
      "testCaseId": "b",
      "summaryReportRequired": "false",
      "postConditionExecution": "ON_SUCCESS"
    }
  ]
};

(function filter(obj) {
    $.each(obj, function(key, value){
        if (value === "" || value === null){
            delete obj[key];
        } else if (Object.prototype.toString.call(value) === '[object Object]') {
            filter(value);
        } else if (Array.isArray(value)) {
            value.forEach(function (el) { filter(el); });
        }
    });
})(sjonObj);

console.log(sjonObj)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Note that if you're willing to use a library like lodash/underscore.js, you can use _.pick instead. However, you will still need to use recursion to filter deeply, since neither library provides a deep filter function.

sjonObj = (function filter(obj) {
    var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });
    return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });
})(sjonObj);

This variant has the added advantage of leaving the original object unmodified, but it does create an entirely new copy, which would be less efficient if you don't need the original object.

var sjonObj = {
  "executionMode": "SEQUENTIAL",
  "coreTEEVersion": "3.3.1.4_RC8",
  "testSuiteId": "yyy",
  "testSuiteFormatVersion": "1.0.0.0",
  "testStatus": "IDLE",
  "reportPath": "",
  "startTime": 0,
  "durationBetweenTestCases": 20,
  "endTime": 0,
  "lastExecutedTestCaseId": 0,
  "repeatCount": 0,
  "retryCount": 0,
  "fixedTimeSyncSupported": false,
  "totalRepeatCount": 0,
  "totalRetryCount": 0,
  "summaryReportRequired": "true",
  "postConditionExecution": "ON_SUCCESS",
  "testCaseList": [
    {
      "executionMode": "SEQUENTIAL",
      "commandList": [
        
      ],
      "testCaseList": [
        
      ],
      "testStatus": "IDLE",
      "boundTimeDurationForExecution": 0,
      "startTime": 0,
      "endTime": 0,
      "label": null,
      "repeatCount": 0,
      "retryCount": 0,
      "totalRepeatCount": 0,
      "totalRetryCount": 0,
      "testCaseId": "a",
      "summaryReportRequired": "false",
      "postConditionExecution": "ON_SUCCESS"
    },
    {
      "executionMode": "SEQUENTIAL",
      "commandList": [
        
      ],
      "testCaseList": [
        {
          "executionMode": "SEQUENTIAL",
          "commandList": [
            {
              "commandParameters": {
                "serverAddress": "www.ggp.com",
                "echoRequestCount": "",
                "sendPacketSize": "",
                "interval": "",
                "ttl": "",
                "addFullDataInReport": "True",
                "maxRTT": "",
                "failOnTargetHostUnreachable": "True",
                "failOnTargetHostUnreachableCount": "",
                "initialDelay": "",
                "commandTimeout": "",
                "testDuration": ""
              },
              "commandName": "Ping",
              "testStatus": "IDLE",
              "label": "",
              "reportFileName": "tc_2-tc_1-cmd_1_Ping",
              "endTime": 0,
              "startTime": 0,
              "repeatCount": 0,
              "retryCount": 0,
              "totalRepeatCount": 0,
              "totalRetryCount": 0,
              "postConditionExecution": "ON_SUCCESS",
              "detailReportRequired": "true",
              "summaryReportRequired": "true"
            }
          ],
          "testCaseList": [
            
          ],
          "testStatus": "IDLE",
          "boundTimeDurationForExecution": 0,
          "startTime": 0,
          "endTime": 0,
          "label": null,
          "repeatCount": 0,
          "retryCount": 0,
          "totalRepeatCount": 0,
          "totalRetryCount": 0,
          "testCaseId": "dd",
          "summaryReportRequired": "false",
          "postConditionExecution": "ON_SUCCESS"
        }
      ],
      "testStatus": "IDLE",
      "boundTimeDurationForExecution": 0,
      "startTime": 0,
      "endTime": 0,
      "label": null,
      "repeatCount": 0,
      "retryCount": 0,
      "totalRepeatCount": 0,
      "totalRetryCount": 0,
      "testCaseId": "b",
      "summaryReportRequired": "false",
      "postConditionExecution": "ON_SUCCESS"
    }
  ]
};

sjonObj = (function filter(obj) {
    var filtered = _.pick(obj, function (v) { return v !== '' && v !== null; });
    return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });
})(sjonObj);

console.log(sjonObj);

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>

这篇关于如何从json对象中删除所有null和空字符串值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆