Passing JSON-encoded HTML from Wordpress to JavaScript
<p>I'm trying to pass a post's content (which may contain HTML) to JavaScript via wp_localize_script(). wp_localize_script() can't handle multi-dimensional arrays, so I'm <a href="http://www.ronakg.com/2011/05/passing-php-array-to-javascript-using-wp_localize_script/" rel="nofollow">encoding it in JSON and then decoding it with jQuery</a>.</p>

<p>That works fine as long as you it's only text and you replace the <code>&amp;quot;</code> entity with a regular <code>"</code> before you call <code>$.parseJSON()</code>. If you try to parse a post with HTML in it, though, you get errors like, </p>

<blockquote>
  <p>JSON.parse: expected property name or '}'
  <a href="http://redacted.local/wp/wp-includes/js/jquery/jquery.js?ver=1.6.1" rel="nofollow">http://redacted.local/wp/wp-includes/js/jquery/jquery.js?ver=1.6.1</a>
  Line 16</p>
</blockquote>

<p>So, I'm guessing I need to do some more string manipulation before trying to parse it, to convert more entities back to the regular characters, but I don't want to just pick the few characters I'm having errors with because I'm sure there are dozens more that I might miss. Is there a comprehensive or standard way of doing this? I've done a lot of searching and having found any answers, so it makes me think I'm missing something obvious.</p>

<p>Here's the PHP side:</p>

<pre><code>public function loadResources()
{
    // ... 

    wp_register_script(
        'bgmp',
        plugins_url( 'functions.js', __FILE__ ),
        array( 'googleMapsAPI', 'jquery' ),
        self::BGMP_VERSION,
        true
    );

    // ...

    if( !is_admin() &amp;&amp; $this-&gt;mapShortcodeCalled )
    {
        // ...

        wp_enqueue_script('bgmp');

        $bgmpData = array(
            'options'   =&gt; $this-&gt;getMapOptions(),
            'markers'   =&gt; $this-&gt;getPlacemarks()
        );
        wp_localize_script( 'bgmp', 'bgmpData', $bgmpData );
    }

    // ...
}

public function getPlacemarks()
{
    // ...

        foreach( $publishedPlacemarks as $pp )
        {
            // ...

            $placemarks[] = array(
                // ...
                'details'   =&gt; $pp-&gt;post_content,
                // ...
            );
        }

    return json_encode( $placemarks );
}
</code></pre>

<p>And here's the JavaScript side</p>

<pre><code>// ...

init : function()
{
    // ...

    bgmpData.markers        = $.parseJSON( bgmpData.markers.replace(/&amp;quot;/g, '"') );

    // ...
},

// ...
</code></pre>
