Gary Court

  • Home
  • About
  • Blog
  • Contact

Blog » Post

« OpenWRT Advanced Firewall VPNC with Shorewall on OpenWRT »

JavaScript DOM to BadgerFish Encoder

The other day, David Sklar decided to come up with an ingenious method translating XML into simple JSON; nicknamed BadgerFish. At about the same time, I was looking for a format in which I could convert XML to JSON without loosing the features of XML yet keeping the JSON objects simple. BadgerFish is about as close as a good format as I have seen. However, a project I am working on requires an XML DOM in JavaScript to be converted into JSON for easier processing. Being that no one has written one yet, I went ahead and wrote my own - and am offering it free for others to use.

There are some differences of my implementation compared to David’s:

  • I don’t treat the xmlns property any more special then any other property. The original BadgerFish spec states that the xmlns property should be on every node. This is overkill for me, so I left it out.
  • I don’t ignore whitespace text nodes.
  • Multiple child text nodes are added to the ‘$’ property as an array.

For limitations of BadgerFish, see the homepage.

Usage example:

<script language="text/javascript" src="BadgerFish.js"></script>
<script language="text/javascript">
document.write(encode(document).toSource());
</script>

This is not the best JavaScript I’ve ever written, as I could have cleaned it up using namespaces and JavaScriptDoc comments, but I wrote it in a hurry. Feel free to tear this apart and use it for your own purposes.

Click here to download.

Leave a Reply

Information

  • Author

    Gary Court
  • Posted

    Thursday, April 27th, 2006 at 9:23 pm
  • Category

    • Web Development
    • JavaScript
  • Tags

    • BadgerFish
    • JSON
    • DOM
    • XML
    • JavaScript
    • code
    • script
    • snipet
    • example
    • sample
    • Ajax
  • Response

    • Comment
    • Trackback
  • Syndication

    • RSS 2.0 Comments
  • Related Posts

    • No related posts
CourtNET

© 2005 Gary Court. All rights reserved. | Valid: XHTML CSS | XFN | Powered by WordPress & Gallery 2.