Passing JSON-encoded HTML from WordPress to JavaScript

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 encoding it in JSON and then decoding it with jQuery.

That works fine as long as you it’s only text and you replace the " entity with a regular " before you call $.parseJSON(). If you try to parse a post with HTML in it, though, you get errors like,

Read More

JSON.parse: expected property name or ‘}’
http://redacted.local/wp/wp-includes/js/jquery/jquery.js?ver=1.6.1
Line 16

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.

Here’s the PHP side:

public function loadResources()
{
    // ... 

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

    // ...

    if( !is_admin() && $this->mapShortcodeCalled )
    {
        // ...

        wp_enqueue_script('bgmp');

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

    // ...
}

public function getPlacemarks()
{
    // ...

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

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

    return json_encode( $placemarks );
}

And here’s the JavaScript side

// ...

init : function()
{
    // ...

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

    // ...
},

// ...

Related posts

Leave a Reply

2 comments

  1. placemarks[] = array( this means that placemarks is array of arrays, is that right?

    also you don’t need to entities back and forth , just call $.parseJSON() on all of the
    bgmpData var:

    var bgmpData_parsed = $.parseJSON( bgmpData);
    

    thin you can access markers by bgmpData_parsed.markers