Typescript debug util – Output json structure to console as formatted and sorted properties

Made a Debug util TypeScript class for formatted output to browser console of json objects, also sorted on property keys alphabetically (usage: simplifies text compare between different json structures).

export class DebugUtils {
  ///Outputs object as formatted json string to console.
  public static ToConsoleJson(value: any, message = null) {
    if (message) {
      console.log(message);
    }
    console.debug(JSON.stringify(value, null, 2));
  }

  ///Outputs object as formatted json string to console sorted alphabetically by property keys.
  public static ToConsoleJsonSortedByKey(obj: any, message = null) {
    //sort object keys alphabetically
    var allKeys = [];
    JSON.stringify( obj, function( key, value ){ allKeys.push( key ); return value; } )
    allKeys.sort();
    const sortedJsonString = JSON.stringify( obj, allKeys, 2);
    if (message) {
      console.log(message);
    }
    console.debug(sortedJsonString);
  }
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *