Skip to content

tokkonopapa/jQuery-parseData

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jQuery-parseData

A simle parser to get the option objects from HTML5 data-* attribute without using eval().

Usage:

Your markup like bellow:

<div data-my-plugin='{"propertyFoo": "foo", "propertyBar": "bar"}'></div>
<div data-my-plugin="{propertyFoo: 'foo', propertyBar: 'bar'}"></div>
<div data-my-plugin="propertyFoo: foo, propertyBar: bar"></div>

will be transfered into the options object:

{
    propertyFoo: "foo",
    propertyBar: "bar"
}

if you use .parseData() in your jQuery plugin like this:

var opts = $(this).parseData('my-plugin');

Example:

See Demo on jsfiddle.

Description:

This plugin consists of two functions - one is a utility function _jsonize() that convert a malformed JSON string into the almost valid JSON, and anoter is a .parseData() that translate a JSON into the JavaScript object.

The .parseData() uses $.parseJSON() which checks validity for JSON using the same logic of Douglas Crockford's json2.js like this:

// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
    .replace( rvalidtokens, "]" )
    .replace( rvalidbraces, "")) ) {

    return ( new Function( "return " + data ) )();
}

It means this plugin has a safety equivalent to the Douglas Crockford's json2.

References:

About

A simle parser to get the option objects from HTML5 data-* attribute without using `eval()`.

Resources

License

Stars

Watchers

Forks

Packages

No packages published