patternjavascriptMinor
JavaScript object to JSON
Viewed 0 times
javascriptobjectjson
Problem
Since I didn't find a way to properly transform JavaScript object to JSON with PHP, I wrote a snippet.
Lets assume the following excerpt from Google Fonts JavaScript API:
This, given straight to PHP's
Since I need this data in JSON after the template has been parsed (working on an exporter), I wrote this snippet (which double-quotes the hell out of this one):
There is no problem with the snippet, it converts my data into PHP array without problems.
My concern, though, is, whether this is the most optimal way of doing it?
Lets assume the following excerpt from Google Fonts JavaScript API:
WebFontConfig = {
google: { families: [ 'Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic,700italic:latin,latin-ext' ] }
};This, given straight to PHP's
json_decode will null out and JSONLint will say it's invalid.Since I need this data in JSON after the template has been parsed (working on an exporter), I wrote this snippet (which double-quotes the hell out of this one):
// gather WebFontConfig arrays
$webfonts = preg_match_all('/(WebFontConfig\s*?=\s*?)\{(.+?)(\};)/s', $scriptData, $fontdata, PREG_SET_ORDER);
// kids, dont do this at home
foreach ($fontdata as $founddata)
{
$original = $founddata[0];
$WFCVariable = $founddata[1];
// leave outer braces only
$usable = str_replace($WFCVariable, '', $original);
$usable = trim($usable, ';');
// transform keys into double-quoted keys
$usable = preg_replace('/(\w+)(:\s*?)(\{|\[)/im', '"$1"$2$3', $usable);
// prepare to transform array wrapping single quotes to double quotes
$lookups = array(
'/(\[)(\s*?)(\')/',
'/(\')(\s*?)(\])/'
);
$replace = array(
'$1$2"',
'"$2$3'
);
$usable = preg_replace($lookups, $replace, $usable);
// decode
$jsoned = json_decode($usable);
// and check
var_dump($jsoned);
}$scriptData essentially is the above JavaScript object trim-extracted out of my template through DOMDocument .. DOMNode->nodeValue.There is no problem with the snippet, it converts my data into PHP array without problems.
My concern, though, is, whether this is the most optimal way of doing it?
Solution
As this works for you and as there is no javascript interpreter in PHP unless you install it (there is a V8 PHP extension IIRC), I would say you did this right so far.
Which else criteria could there be than your own ones? You should probably write unit and acceptance tests for it. And remove the
Which else criteria could there be than your own ones? You should probably write unit and acceptance tests for it. And remove the
var_dump debug cruft out of it. But by the way you do this on it's own, it does not look too far off.Context
StackExchange Code Review Q#25653, answer score: 2
Revisions (0)
No revisions yet.