Lindsey Kuper (lindseykuper) wrote,
Lindsey Kuper
lindseykuper

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"] = "http://psychology.lindseys-job.com/flashcards/chapter8/section3/yes/this/is/fake/";
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": "http://psychology.lindseys-job.com/flashcards/chapter8/section3/yes/this/is/fake/",
"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
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 6 comments