2

Can we somehow write a JSON string in html data tag attribute?

Then process it in javascript to parse as a normal JSON object.

Example:

HTML

<select class="field" data-select="{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}"></select>

JS

var obj = JSON.parse($('form').find('select').attr('data-select'));

Solution using single quotes:

<select class="field" data-select='{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}'></select>
0

1 Answer 1

4

Use JSON.stringify (if javascript) to make the json a string and sotre it in the data-* field.

var json = {"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]};
var div = document.getElementById("myDiv");
div.setAttribute("data-json", JSON.stringify(json));
alert(div.getAttribute("data-json"))

Check the template engine docs (if you are you are using one) to generate the stringified json.

Fiddle: https://jsfiddle.net/b1tqxhty/

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

1 Comment

Was needed only single quotes in wrapping string of "data-select" attribute.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.