Posted on February 17, 2014 by

JSON Formatting Trick

I like my to JSON look pretty. Even if I have to break a rule or two.

So this is a bit hacky. I’ll say that right away, but I’m okay with that.

I like to store all of my site’s content in a central document where it is easily editable.  Currently my format of choice is JSON, which is great… for the most part. My biggest annoyance with JSON is that it doesn’t allow line returns or tabs within a string of text. For example, If I were to use JSON to contain lyrics of a song I might want to format it like so:

{
	"title": "Weezer - In The Garage",
	"lyrics": "
		I've got the Dungeon Master's Guide. <br/>
		I've got a 12-sided die. <br/>
		I've got Kitty Pryde <br/>
		And Nightcrawler too <br/>
		Waiting there for me. <br/>
		Yes I do, I do. 
	"
}

Unfortunately that JSON will not parse due to the line returns and tabs within the lyrics string. To get that to parse I’d need to place all of the lyrics in a single line, which would be fugly and hard to edit later. So I came up with a workaround. 

First off, here is a standard way that you might load a JSON file with JQuery:

$.ajax({
	dataType: "json",
	url: "lyrics.json",
	success: function (data){
		// place the data into our DOM
		$("#titleContainer").html(data.title);
		$("#lyricsContainer").html(data.lyrics);
	}
});

Simple enough, but my JSON isn’t ready to parse so here is my fix:

$.ajax({
	dataType: "text",
	url: "lyrics.json",
	success: function (data){
		data = data.replace(/(\r\n|\n|\r)/gm,"");
		data = data.replace(/\t/g, '');
		data = $.parseJSON(String(data));
		
		// place the data into our DOM
		$("#titleContainer").html(data.title);
		$("#lyricsContainer").html(data.lyrics);
	}
});

First I’m loading the JSON with a dataType of “text” instead of “json” so that JQuery doesn’t automatically try to parse it. Once I have the data as a text object I use the replace function to remove the line returns and tabs which would keep it from parsing correctly. Once that’s done I can parse the JSON and it will work great.

I’m not sure if people will think this is a good idea or not, but it allows me to format my JSON in a visually appealing manner.

UPDATE: It looks like Douglas Crockford recommends a similar approach to adding comments to a JSON file. He says to add them, and just remove before parsing. I’ll probably add a regular expression to remove comments in addition to line returns and tabs.