user2042985
user2042985

Reputation: 105

PHP array with JavaScript objects to JavaScript

If I have an array in JS like this:

{
 "car": "BMW",
 "count": 7 
}

I can generate it from PHP quite easy using this array:

array(
       'car' => 'BMW',
       'count' => 7,
)

and json_encode. This is not a problem.

But what if I have an array in JS like this:

{
   "center": new google.maps.LatLng(-34.397, 150.644),
   "zoom": 8
}

is there also some nice way how to produce it from PHP?

The method above fails because JSON put quotes around "new google.maps.LatLng(-34.397, 150.644)".

Upvotes: 1

Views: 99

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123453

JSON doesn't support custom types. It's just meant for passing data and to be available to any consumer, whereas google.maps.LatLng() isn't really "data."

So, you'll have to accomplish this in 2 steps:

  1. You can include the values needed in another PHP array for the JSON:

    array(
        'center' => array(
            'lat' => -34.397,
            'lng' => 150.644
        ),
        'zoom' => 8
    )
    
    {
        "center": {
            "lat": -34.397,
            "lng": 150.644
        },
        "zoom": 8
    }
    
  2. Then, once parsed to a JavaScript Object, say data:

    data.center = new google.maps.LatLng(data.center.lat, data.center.lng);
    

    And, if there are numerous examples of such objects in the data, you can specify a reviver function to try to recognize them and create the instances:

    // parse, creating `google.maps.LatLng` from any { lat: ..., lng: ..., ... }
    var data = JSON.parse(jsonString, function (key, value) {
        if (typeof value === 'object' && value.lat && value.lng) {
            return new google.maps.LatLng(value.at, value.lng);
        } else {
            return value;
        }
    });
    

    Example: http://jsfiddle.net/XXbUU/


Side note: JSON and JavaScript make a stronger distinction between "array" types than PHP does.

  • "Associative" arrays in PHP become Objects in JSON and JavaScript.
  • "Non-associative" arrays in PHP become Arrays in JSON and JavaScript.

Upvotes: 2

Related Questions