Fork Me

defiant.js

defiant.js provides the ability for you to build smart templates and query selections applicable on JSON objects - based upon standardized technologies such as XSLT & XPath.

Download defiant.js  

Suggestions,
problems,
feedback?

Check out the issues list Github

Overview

Contemporary Javascript templating libraries out there offers ways for you to write simplistic templates. Though problems arises when the needs of real-world development requires the ability to write logical/intelligent templates and in such scenarios, those templates needs to be supplemented with helper functions - which in turn results in scattered templating...and that is bad practice.

With defiant.js, you can write logical templates with powerful technologies such as XSLT & XPath, applicable on JSON objects. Besides the fact that XSLT is a proven Turing-complete language, it is also standardized and supported by all major browsers. Furthermore, defiant.js is the only Javascript library that offers fullscale XPath implementaion on JSON objects, as opposed to the smart but unstandardized JSONPath. Try out the XPath Evaluator below to get the idea.

You could say that defiant.js joins XML and related technologies with JSON.
Most likely, Douglas Crockford will hate this unholy matrimony.

Usage

Using defiant.js is pretty easy. Check out the examples below to get a hint of how it can be used; the first one is rather simple and the latter is more advanced and exemplifies calling templates from another template. It contains recursive template calling and renders a fictitious filesystem structure. When "tree-walker" template is calling itself, indentation is passed as argument, thus indenting child elements of a folder.

To see the code below in action, here are the demo files; simple example and advanced example

Simple example

Advanced example

XPath

One powerful tool when dealing with XML is the advantage of using XPath. XPath is a standardized language for addressing parts of an XML document and enables features such as analysis, transformation & refined data selection out of an XML structure. The lack of this tool when dealing with JSON has conveyed in initiatives with diverse prosperities and introduced suggestion of JSONPath, that has not been standardized (nor wideley absorbed by the community).

By using defiant.js, the power of XPath can be unleashed on JSON objects, without the need of a new set of expressions & syntax, as has been with JSONPath.
No re-schooling is required :-)

Expressions table

The syntax table below is a incision of the power that XPath brings. XPath has a lot more to offer. An important advantage of implementing XPath, as contrasted with JSONPath, is that this language has been documented a great deal on the web and information & how-to's can easily be found & digested.

Expression Description
/ Child operator; selects immediate children of the left-side collection. When this path operator appears at the start of the pattern, it indicates that children should be selected from the root node.
// Recursive descent; searches for the specified element at any depth. When this path operator appears at the start of the pattern, it indicates recursive descent from the root node.
. Indicates the current context.
.. The parent of the current context.
* Wildcard; selects all elements regardless of the element name.
@ Attribute; prefix for an attribute name.
@* Attribute wildcard; selects all attributes regardless of name.
[] Subscript operator; applies a filter pattern OR used for indexing within a collection.
| Union operator; results in a combination of element sets
() Groups operations to explicitly establish precedence

In order to access XPath functionality easily, some global objects has been extended with useful methods, for instance; JSON.search. Detailed information about these extension can be found in the Function reference section.

XPath Evaluator

Not familiar with XPath? Don't worry, use the XPath evaluator below and you will become an expert in no time.

A couple of suggestions:

  • Switch views from XML to JSON to get a better overview of the data structure and how the selections are made.
  • Also, check out the browser console for hints.
  • To get going, click any of the pre-written examples of XPath queries.
  • Check out these files to see the functions individually visuablized; JSON to XML, XML to JSON and JSON Search. Use these files to get acquainted with the functions and get the picture of the transformation rules.

Caveats

There are some internal procedures of defiant.js as well as known limitations of JSON (compared to XML) that you should be aware of. Below are some knowledge to keep in mind when working with XSLT, XPath and JSON.

  • The structure of object that contains attributes keys (starting with "@"), will be altered and attributes precedes regular regular elements in the object structure.
  • Namespace selection is not possible, since JSON does not support such detailed data semantics (as opposed to XML).
  • Searching '//*' in JSON will result in one less match (comparing same search with XML), since XML has a root node and the handle to that match is "reachable". JSON's root handle is the name of the objects variable name and is out of scope for the search algorithm. Hence, a handle to the variable name can't be passed back to the querist.
  • defiant.js transforms JSON to XML, which is done lossless. This means that everything from the source data structure can be interpreted back. Transforming XML to JSON is not lossless since JSON isn't built to match the same level of data semantics as XML.

Function reference

Besides smart templating with the ability to perform transformations using XSLT on XML, & JSON structures, defiant.js is equiped with powerful methods for refined data selections and generic tools to analyze & manipulate these structures programmatically, implemented cross-browser.

Defiant.render(template, object)
Inline script-block(s) delivers XSLT templates to the browser and can contain multiple templates. Pass the name of the template that will be used on the JSON object - passed in as second argument. This function returns an HTML string of the transformation.

Defiant.xmlFromString(xml_string)
This function does exactly what its name indicates; it creates and returns an XML document from the string passed in as argument. This function is primarily used internally by defiant.js.

Defiant.node.toJSON()
This function does exactly what its name indicates; transforms a node and its descending structure into JSON equivalent.

Defiant.node.selectNodes(xpath)
There are different ways of dealing with XPath in Internet Explorer & other browsers. This function is not supported by all browsers by default but the syntax is much clearner & simpler than xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE, null); and therefore implemented cross browser with defiant.js.

Defiant.node.selectSingleNode(xpath)
This function behaves almost the same way as selectNodes with the difference that it returns the first match of the XPath expression and exits the search algorithm as soon as the first match is found. It is a preferable alternative if a single node is known to be desired, hence better choise performance-wise.

Defiant.node.prettyPrint
This property is a good helper when writing & debugging XML centric code. It's a shorthand way to get the serialized representation of a node, as opposed to creating a new XMLSerializer and call its function serializeToString. This property outputs a human-readable version of the serialized XML string, i.e. with line breaks and tabbed rows. Lastly, this property is accessible from all element nodes, regardless of depth in the XML structure (the document node included).

JSON.toXML(object)
With defiant.js, it is trivial to convert your JSON object into XML structure. Just call this extended function of the global object JSON and pass in your object as argument & the function will return an XML document.

JSON.search(object, xpath, first)
This function is the jewel of defiant.js. Call this function whenever you want a collection of elements in a JSON object, matching the XPath query, given as second argument. The third argument is optional and is of boolean type; if set to true, the function exists the search algorithm, as soon as a matching element is found, based upon given XPath.
The function JSON.search returns an array with agregate functions, populated with matching elements. Besides the ability find elements with XPath, this function returns references to the matching elements in the JSON structure. Put differently; the matched elements can be altered with a loop, thus altering the original JSON object. See the code below as example.

Source

About

powered by defiant.js