\n","image":"https://explain.codes/media/static/images/eightify-logo.svg","author":{"@type":"Person","name":"Nikita Barsukov","url":"https://explain.codes//author/nikita-barsukov"},"publisher":{"@type":"Organization","name":"Rational Expressions, Inc","logo":{"@type":"ImageObject","url":"https://explain.codes/landing/images/[email protected]"}},"datePublished":"2024-10-24T18:15:01.760Z","dateModified":"2024-10-24T18:15:03.559Z"}
Explain Codes LogoExplain Codes Logo

Best way to store JSON in an HTML attribute?

html
data-attributes
json-parsing
security-best-practices
Nikita BarsukovbyNikita BarsukovยทOct 24, 2024
โšกTLDR

HTML5 data-* attributes are your friends for embedding JSON in HTML. Serialize your JSON object with JSON.stringify(), store it in the attribute, then retrieve and parse it back into a JSON object using JSON.parse() and getAttribute().

<div id="example" data-json='{"key":"value"}'></div> <script> var jsonObj = { key: "value" }; // Let's put that JSON in... Well, not so secret place document.getElementById("example").dataset.json = JSON.stringify(jsonObj); var jsonStr = document.getElementById("example").dataset.json; // Voila! JSON retrieved and parsed ๐Ÿ‘ console.log(JSON.parse(jsonStr)); </script>

Handling Special Characters & Large Data

Special characters can break your brain... I mean, your markup or code. So, here's how you handle them:

  • Base64 Encoding: Special characters need special treatment. You could use server-side json_encode() that plays nicely with atob() and JSON.parse().

  • Script Tags to the Rescue: Got a hefty JSON to deal with? Use a <script> tag with type="application/json". Stick an ID on it to find it easily later, it's not going anywhere.

  • Character Escaping: Make ', ", &, <, and > safe using specific functions or libraries. They can't hurt you if they're escaped!

  • Inject Safe Practices: Treat client data as potential tricksters. Always sanitize and validate it server-side to prevent XSS and other scary stuff.

Friendly with Accessibility & SEO

Ensuring your stored JSON data is accessible and SEO-friendly is a good citizen's duty. Have some tips:

  • ARIA Attributes: Use aria-label or aria-describedby to relate data attributes to elements. Accessibility techs will be grateful.

  • HTML5 Compatibility Checks Needed: Watch out for the good ol' browser support for the data- attributes*. Use polyfills if were born too early.

The Right Storage Method for the Right JSON

Data comes in different shapes and sizes. Know your JSON to store it right:

  • Small JSON/piece of cake: Just slap it into data- attributes*. They can handle it.

  • The Beastly JSON/feast: Get a <script> tag and set the type to application/json.

  • The Moody JSON/party crasher: For JSON that changes with user interactions, go JavaScriptic with dynamic DOM updates.

Beef-Up Your Security

The internet can be a haunted house with injection attacks, XSS, etc. Say โ€˜Boo!โ€™ back with these safety precautions:

  • Content Security Policy (CSP): Take control of the data you load with CSP headers. It's like having a bouncer.

  • UTF-7 Encoding Attacks?: Protect yourself by encoding "+" signs. They're not as positive as they look in UTF-7.

  • Safe JSON Parsing: Always use try...catch blocks when parsing. Caution is the parent of safety.

  • Avoid Inline Event Handlers: Use addEventListener instead of onclick. We like our JSON inside, not inline.