Google Logo

Parsing der Google Currency JSON Antwort als PHP ArrayParse Google Currency JSON response as PHP array

Unfortunately Google’s currency converter ( does not return JSON data that can be directly parsed by PHP’s json_decode as its keys are not enclosed in (double) quotes.

For instance, the following call to will return something like the following depending on the current conversion rate:

{lhs: "1 Euro",rhs: "1.3026 U.S. dollars",error: "",icc: true}

Thus, the keys lhs, rhs, error and icc are not enclosed in quotes, causing PHP’s json_decode to fail (to return NULL).

A simple and effective solution is to do some simply pre-processing before handing the raw JSON data to json_decode. The following code snippet describes an approach to add missing (double) quotes to the JSON keys returned by Google’s converter:

$googleJson = '...';
$phpJson = preg_replace("/((\"?[^\"]+\"?)[ ]*:[ ]*([^,\"]+|\"[^\"]*\")(,?))/i", '"\2": \3\4', str_replace(array('{', '}'), array('',''), $googleJson));

This call does nothing more than replacing the enclosing square brackets ({}) in order to add double quotes are keys and values contained in the JSON string (if they don’t already exist).

The resulting string can be used together with the now missing square brackets to produce a JSON string that can be processed by json_decode directly.

Generally speaking, this simple call be used to add enclosing brackets for any JSON string given.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.