Lindsey Kuper (lindseykuper) wrote,
Lindsey Kuper

JSON is good for something other than replacing XML!

So I had a big ol' generated JavaScript array of things like:

resources["psych_flashcards_8_3_0"] = new Array();
resources["psych_flashcards_8_3_0"]["name"] = "Flashcards: Operant Conditioning";
resources["psych_flashcards_8_3_0"]["url"] = "";
resources["psych_flashcards_8_3_0"]["type"] = "Flashcards";
resources["psych_flashcards_8_3_0"]["fileFormat"] = "html";

One of those for every index. 1422 indices. 7110 lines. 643 KB of JavaScript.

lindseykuper: It's a friggin' enormous .js file. There's probably a more efficient way for me to do that associative array
lindseykuper: like, an object or something
jes 5 1 9 9: javascript doesn't actually do much to distinguish between objects and arrays
jes 5 1 9 9: but you should have a look at JSON
lindseykuper: I've used it. I like it.
lindseykuper: yeah, that totally makes sense for this.
jes 5 1 9 9: I think your resources structure can be represented as JSON without changing any of the other javascript

I thought, "No way. No, it can't." But it turns out it totally can. Now I've got an object of things like

"psych_flashcards_8_3_0": {
"name": "Flashcards: Operant Conditioning",
"url": "",
"type": "Flashcards",
"fileFormat": "html"

It comes out to 374 KB. 40% less code, and the cool part is that nothing else had to change, because all my old code that used the double array indices still works. How great is that?

Okay, so this isn't rocket science, and a native speaker of JavaScript would probably have done something object-y right from the start instead of mucking about with huge two-dimensional associative arrays. But still, this is neat. I didn't know that objects and arrays were that interchangeable. And I've never heard of anyone using JSON for anything other than replacing XML.

Tags: programming

  • Some victories

    In the last two days: I sent a draft of my dissertation to my committee! There are some parts that aren't quite finished; it's a…

  • My dissertation abstract

    So I need to write an abstract for my dissertation. Anyone wanna glance over this and tell me what you think? If you suggest any edits, keep in…

  • What December's been like so far

    Alex oniugnip has already written about what December has been like for us so far. Here's the story from my perspective. At the…

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded