Escaping/encoding single quotes in JSON encoded HTML5 data attributes

When embedding JSON data in HTML5 data attributes, single quotes can break HTML parsing. JavaScript provides several methods to properly escape or encode single quotes to ensure valid HTML output.

The Problem with Single Quotes in Data Attributes

Single quotes inside JSON values can break HTML attribute parsing when the attribute itself uses single quotes:

// Problematic - single quote breaks HTML
<div data-info='{"name": "John's Car"}'>

Method 1: Using JSON.stringify() with Replace

The most common JavaScript approach is to use JSON.stringify() and replace single quotes:

<!DOCTYPE html>
<html>
<body>
    <div id="output"></div>
    
    <script>
        let data = {
            name: "John's Car",
            type: "SUV",
            tags: ["family", "big"]
        };
        
        // Escape single quotes for HTML attribute
        let jsonString = JSON.stringify(data).replace(/'/g, '&#39;');
        
        // Create HTML with data attribute
        let html = `<article data-info='${jsonString}'>Vehicle Info</article>`;
        
        document.getElementById('output').innerHTML = html;
        
        // Verify we can read it back
        let article = document.querySelector('article');
        let parsed = JSON.parse(article.dataset.info);
        console.log('Parsed data:', parsed.name);
    </script>
</body>
</html>

Method 2: Using Double Quotes for Attributes

A simpler approach is to consistently use double quotes for HTML attributes:

<!DOCTYPE html>
<html>
<body>
    <div id="container"></div>
    
    <script>
        let userData = {
            message: "It's a beautiful day!",
            items: ["apple", "banana"]
        };
        
        // No escaping needed when using double quotes for attribute
        let jsonStr = JSON.stringify(userData);
        
        let element = document.createElement('div');
        element.setAttribute('data-user', jsonStr);
        element.textContent = 'User Data';
        
        document.getElementById('container').appendChild(element);
        
        // Read back the data
        let storedData = JSON.parse(element.dataset.user);
        console.log('Message:', storedData.message);
    </script>
</body>
</html>

Method 3: HTML Entity Encoding

For complete safety, encode all special HTML characters:

<!DOCTYPE html>
<html>
<body>
    <div id="result"></div>
    
    <script>
        function htmlEncode(str) {
            return str.replace(/&/g, '&amp;')
                     .replace(/</g, '&lt;')
                     .replace(/>/g, '&gt;')
                     .replace(/"/g, '&quot;')
                     .replace(/'/g, '&#39;');
        }
        
        let complexData = {
            html: "<script>alert('test')</script>",
            quote: "He said 'Hello'"
        };
        
        let safeJson = htmlEncode(JSON.stringify(complexData));
        
        // Safely embed in HTML
        document.getElementById('result').innerHTML = 
            `<p data-complex='${safeJson}'>Safe Data</p>`;
            
        // Retrieve and parse
        let p = document.querySelector('p');
        let retrieved = JSON.parse(p.dataset.complex);
        console.log('Retrieved:', retrieved.quote);
    </script>
</body>
</html>

Comparison

Method Pros Cons
Replace single quotes Simple, targeted fix Only handles single quotes
Double quote attributes Cleanest, no escaping needed Must be consistent
Full HTML encoding Handles all special characters More verbose output

Best Practices

Always use double quotes for HTML attributes containing JSON data, and validate that your JSON can be properly parsed after embedding.

Conclusion

The safest approach is using double quotes for HTML attributes to avoid escaping issues. For complex data with multiple special characters, use full HTML entity encoding to ensure valid markup.

Updated on: 2026-03-15T23:18:59+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements