JSON Facepalm

I’ve only recently been dabbling in the world of JSON, and I’m realizing that it is an excellent alternative to XML. Being fairly new to it, however, has found me on a few code-based wild goose chases. For a side project I’m working on, I decided it would be slick to have the chosen value from one HTML select element populate. I found a few code samples and hacked them together to work for my form.

Using the jQuery function $.getJSON, I had it running in no time. Now, keep in mind I was testing in Firefox. More often then not, when I put something together in javascript or jQuery it seems to work flawlessly in Firefox. But when I come to check it in Chrome or Safari, something is amuck.

Have spent a good twenty minutes on the Google tubes searching for what could be the matter, I came up empty handed. After some debugging in the ten line jQuery script, I realized that data from my JSON response wasn’t being passed along. To the JSON I went! And that’s where I found the issue:

[{"key0": "value0", "key1": "value1"},{"key0": "value2, "key1": "value3"},]

Hanging out at the tail end of the string was the wayward ‘,’! No doubt the result of some careless output from the database. It worked like a charm in Chrome after cleaning it up with a simple line of PHP before adding the final ‘]’:

$output = substr($output,'',-1);

So, as you can see, it wasn’t a case of ajax not working in Chrome, but rather a case of invalid JSON working in Firefox. While I appreciate Firefox’s leniency, this isn’t the first time it has bit me the ass. But, in the end, a great lesson learned regarding the output of valid JSON.

Leave a Reply

About

mhokieAs a computer science nerd, I enjoy dabbling in all things related to web development and programming. Be it wrangling HTML/CSS across several browsers or harnessing the power of Objective-C while developing iPhone Apps, I enjoy a challenge.

I've recently become a champion of fermentation and all the great things it can do for your body. For the last year or so, I've been dabbling in sauerkraut, kimchi, mead and beer.

My goal for this site is that by posting information regarding my experiences, it will help others where the internets have fallen short. If you have any questions, feel free to contact me, or find me on twitter, @mhokie.

Sponsors

Archives

Categories

Blogroll