I've some PHP source code that are simple key-value arrays like these:
return array('var1' => 'var2' );
And
return array('sub' => array( 'var1' => 'var2' ) );
And I need to parse them into JavaScript objects, because I've a JavaScript implementation of a PHP library and I want to test the compatibility using the original test cases.
There are over a 100 tests, so manual conversion is not practical.
Is there an easy way to convert these into JavaScript objects without using PHP?
This should work!
<?# somefile.php ?>
<script type="text/javascript">
var json = '<?= json_encode(array('sub' => array( 'var1' => 'var2' ))) ?>';
var object = JSON.parse(json);
console.log(object);
</script>
Output
{
sub: {
var1: "var2"
}
}
More commonly, you will see a language-agnostic API which simply provides JSON responses. You could easily test this using asynchronous requests to the API from JavaScript (in-browser, via Node.js, etc.);
If I understood you correctly, you need to use json_encode() like this:
return json_encode(array('sub' => array( 'var1' => 'var2' )));
The returned value: {"sub":{"var1":"var2"}}
To actually answer your question – how to parse PHP's associative arrays to JSON without using PHP – let's use some JavaScript code.
"array('sub' => array( 'var1' => 'var2' ) );".replace(/array\(/g, '{').replace(/\)/g, '}').replace(/=>/g, ':').replace(/;/g, '').replace(/'/g, '"');
This is assuming you just happen to sit on some source code and want to copy it into a Node.js application, and that all the data looks exactly like this. If the data happens to be on multiple lines, if you even want to parse away the "return"/";" parts, if some of the data contains indexed arrays, or if any of the values contain the string I just naively parse away, you'll have to make this script a bit smarter.
And as others have said, if you're interacting with a PHP service, just use json_encode().
You can use json_encode() in PHP and JSON.parse() in JavaScript.