Parse PHP Arrays in JavaScript

2019-04-11 20:49发布

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?

4条回答
劫难
2楼-- · 2019-04-11 21:32

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.);

查看更多
Evening l夕情丶
3楼-- · 2019-04-11 21:38

You can use json_encode() in PHP and JSON.parse() in JavaScript.

查看更多
叼着烟拽天下
4楼-- · 2019-04-11 21:43

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"}}

查看更多
Luminary・发光体
5楼-- · 2019-04-11 21:50

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().

查看更多
登录 后发表回答