Search code examples
jsonnode.jspretty-print

Format the pretty JSON object


I'm using Node.js to pretty-print a JSON object. This line

obj = JSON.stringify(obj, null, 1); 

results in:

 {
  "name": "Member",
  "type": "object",
  "properties": {
   "Id": {
    "type": "GUID",
    "description": "Unique identifier"
   },
   "Name": {
    "type": "string",
    "description": "Members name"
   }
  }
 }

But I want it to look this way:

 {
  "name": "Member",
  "type": "object",
  "properties": {
   "Id": {"type": "GUID", "description": "Unique identifier"},
   "Name": {"type": "string", "description": "Members name"}
  }     
 }

How can I do this?


Solution

  • Use JSON.stringify, then use some regular expressions on the resulting string.
    First strip the top level braces, then replace every newline within a {...} group with blank.