Search code examples
jsonangularstringify

Send unassigned JSON properties to server when using stringify i.e. retain properties name whether property value is empty/null


I have two model properties:

ng-model="category.name"    mandatory field
ng-model="category.desc"    optional

This is how I am sending data to the server (ASP.net)

var rdt = "{'dt':" + JSON.stringify($scope.category) + "}";

However, if an optional property has an unassigned value, the property name is not found server side and gives an error. Are there any ways to retain unassigned properties of JSON?


Solution

  • You have several solutions:

    • Solution 1: Initialize the variables in your scope for example:

    $scope.category.desc = null
    
    • Solution 2: Create a function to take care of that

    function ToJson(object, properties) {
       var result = {};
       for(var i = 0; i < properties.lenght; i++) {
          var property = properties[i];
          if(!object[property]) {
             result[property] = null;
          } else {
             result[property] = object[property];
          }      
       }
    
      return JSON.stringify(result);
    }
    
    // And then use it like this:
    var rdt = "{'dt':" + ToJson($scope.category, ["name", "desc"]) + "}";