在JavaScript中解析PHP数组 [英] Parse PHP Arrays in JavaScript
问题描述
我有一些PHP源代码是这样的简单键值数组:
I've some PHP source code that are simple key-value arrays like these:
return array('var1' => 'var2' );
和
return array('sub' => array( 'var1' => 'var2' ) );
我需要将它们解析为JavaScript对象,因为我有一个PHP库的JavaScript实现并且我想使用原始测试用例测试兼容性。
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.
有超过100个测试,因此手动转换不实用。
There are over a 100 tests, so manual conversion is not practical.
有没有一种简单的方法可以在不使用PHP的情况下将这些转换为JavaScript对象?
Is there an easy way to convert these into JavaScript objects without using PHP?
推荐答案
要实际回答你的问题 - 如何在不使用PHP的情况下将PHP的关联数组解析为JSON - 让我们使用一些JavaScript代码。 / p>
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, '"');
这假设你恰好碰巧查看一些源代码,并希望将其复制到 Node.js 应用程序中,所有数据看起来都是这样的。如果数据恰好在多行上,如果你甚至想要解析return/;部分,如果某些数据包含索引数组,或者任何值包含我只是天真地解析的字符串,你必须使这个脚本更聪明。
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.
正如其他人所说,如果你是int使用PHP服务进行收集,只需使用 json_encode()
。
And as others have said, if you're interacting with a PHP service, just use json_encode()
.
这篇关于在JavaScript中解析PHP数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!