-1

Like explained in a similar Stack Overflow question, in vanilla JavaScript, I can do the following:

var data = Object.assign({}, element.dataset);

... in order to get all data-* attributes as an object.

However, the resulting object is not a "real" JSON object, booleans and numbers are surrounded by quotes.

<div id="my-element"
    data-string="It's OK."
    data-bool="true"
    data-number="10">
</div>

Here is the comparison between vanilla JavaScript and jQuery:

vanilla

jquery

I supposed that in jQuery, jQuery('#my-element').data() is doing the heavy job of "lifting" the data before returning the actual JSON.

Since I'd like to use ES6 and not jQuery, and I don't want to reinvent the wheel (parsing that values using regex/conditions), I'm asking if there is a quick way to do this job.

TylerH
  • 20,799
  • 66
  • 75
  • 101
gremo
  • 47,186
  • 75
  • 257
  • 421
  • So, small point, but an important point that you seem to be confused on. There is no such thing as a JSON Object. JSON is a string. The JSON value may contain the syntax for an object, but it is not an object. It is a string. And the things you are console logging are not JSON. They are just Objects. – Taplar May 05 '20 at 16:51
  • Sorry for being so inaccurate, yep I'm still learning JavaScript. Thanks for the clarification. – gremo May 05 '20 at 16:52

1 Answers1

1

The data processing in jquery is done in getData() function in data.js

here is the code from JQuery library:

function getData( data ) {
    if ( data === "true" ) {
        return true;
    }

    if ( data === "false" ) {
        return false;
    }

    if ( data === "null" ) {
        return null;
    }

    // Only convert to a number if it doesn't change the string
    if ( data === +data + "" ) {
        return +data;
    }
    //Replaced rbrace with regex value.
    if ( /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/.test( data ) ) {
        return JSON.parse( data );
    }

    return data;
}

you can use this function and update your data.

Shub
  • 2,686
  • 17
  • 26
  • How this is supposed to be called? Loop or recusive call or JSON reviver? – gremo May 05 '20 at 17:56
  • You loop into your object values and feed values to this function and replace with returned value. – Shub May 05 '20 at 18:43