0

I want to pass some data from html to jquery using data-attribute like this:

<div data-frames="[
    { src: 'artwork-96.png',  sizes: '96x96',   type: 'image/png' },
    { src: 'artwork-128.png', sizes: '128x128', type: 'image/png' },
    { src: 'artwork-192.png', sizes: '192x192', type: 'image/png' },
    { src: 'artwork-256.png', sizes: '256x256', type: 'image/png' },
    { src: 'artwork-384.png', sizes: '384x384', type: 'image/png' },
    { src: 'artwork-512.png', sizes: '512x512', type: 'image/png' }
]"></div>

I don't know a way how could I use this structure in jquery so it keeps the same format (array with objects). Is there a way to do this?

Using string.split(',') doesn't help me here.

1
  • Is that format fixed or is it your own, and can you make slight changes? Commented Apr 2, 2017 at 12:53

5 Answers 5

5

If you swap the use of single and double quotes (to make it JSON compliant), the jQuery data method does the JSON parsing on-the-fly:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). [ ... ]

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names.

Demo:

// jQuery recognises JSON:
console.log($('div').data('frames'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-frames='[
    { "src": "artwork-96.png",  "sizes": "96x96",   "type": "image/png" },
    { "src": "artwork-128.png", "sizes": "128x128", "type": "image/png" },
    { "src": "artwork-192.png", "sizes": "192x192", "type": "image/png" },
    { "src": "artwork-256.png", "sizes": "256x256", "type": "image/png" },
    { "src": "artwork-384.png", "sizes": "384x384", "type": "image/png" },
    { "src": "artwork-512.png", "sizes": "512x512", "type": "image/png" }
]'></div>

Sign up to request clarification or add additional context in comments.

2 Comments

precise and perfect answer. didn't know that the data attribute does the JSON parsing
would appreciate your inputs on my edited answer below
2

JSON.stringify(your_data) before assigning it to data-frames. And while fetching, JSON.parse(your_data) before using.

EDIT: Since the data is not in the correct JSON format, there are two ways of accessing it using javascript.

  1. As pointed out by @trincot, put formatted JSON to your data-frames, and then access it using .data method. Note: If the data is not in proper JSON format (just like it is seen in the question) the 2nd way (point #2 below) will work.
  2. Using eval("("+your_data+")") will evaluate your data string into a javascript object. You can only then use JSON methods on it (i.e. after evaluation).

After using both the ways (fiddle here with lots of console logs), I think the 1st one would be a better solution (as pointed out by @trincot)

2 Comments

Instead of suggesting eval(), suggest JSON.parse() like you did before. It is safer as it only accepts ... JSON (no functions, side-effects...). But now I see you propose it to deal with the non-JSON format. I would not go that way though. eval has a bad name.
yes i found eval opens doors to threats but i was struggling to parse the unformatted json string, and the only way i found to parse it was through evaluating the string enclosed by parens
0

JavaScript is a better tool for storing complex data versus HTML. I'd change your solution so that your element contains a reference to a data structure in your JavaScript instead of the raw data itself:

var data = {
    someUniqueKey: [
        { src: 'artwork-96.png',  sizes: '96x96',   type: 'image/png' },
        { src: 'artwork-128.png', sizes: '128x128', type: 'image/png' },
        { src: 'artwork-192.png', sizes: '192x192', type: 'image/png' },
        { src: 'artwork-256.png', sizes: '256x256', type: 'image/png' },
        { src: 'artwork-384.png', sizes: '384x384', type: 'image/png' },
        { src: 'artwork-512.png', sizes: '512x512', type: 'image/png' }
    ]
};

$('div[data-frames]').each(function(i, el) {
    var key = $(el).data('frames');

    console.log(data[key]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-frames="someUniqueKey"></div>

Comments

0

If the dataset is rigid then in pure JS you can do as follows

var datas = document.getElementById("datas");
     data = JSON.parse(datas.dataset.frames.replace(/(\w+):\s*'([\w\:\.\-\\\/]+)'/g, "\"$1\": \"$2\""));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<div id="datas" data-frames="[
    { src: 'artwork-96.png',  sizes: '96x96',   type: 'image/png' },
    { src: 'artwork-128.png', sizes: '128x128', type: 'image/png' },
    { src: 'artwork-192.png', sizes: '192x192', type: 'image/png' },
    { src: 'artwork-256.png', sizes: '256x256', type: 'image/png' },
    { src: 'artwork-384.png', sizes: '384x384', type: 'image/png' },
    { src: 'artwork-512.png', sizes: '512x512', type: 'image/png' } ]"></div>

Comments

-1

You can use the parseJSON() function of jQuery.

https://api.jquery.com/jQuery.parseJSON/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.