Reputation:
A JSON array has the form:
[[a,b,c],[a,b,c],[a,b,c]]
Is there a better way than split?
Upvotes: 2
Views: 8472
Reputation: 359776
No, this is most certainly not the best way to parse JSON. JSON parsers exist for a reason. Use them.
In JavaScript, use JSON.parse
:
var input = '[[1,2,3],[1,2,3],[1,2,3]]';
var arrayOfArrays = JSON.parse(input);
In PHP, use json_decode
:
$input = '[[1,2,3],[1,2,3],[1,2,3]]';
$arrayOfArrays = json_decode($input);
Upvotes: 9
Reputation: 14777
You do not need to use regular expressions. As has been mentioned, you must first have valid JSON to parse. Then it is a matter of using the tools already available to you.
So, given the valid JSON string [[1,2],[3,4]]
, we can write the following PHP:
$json = "[[1,2],[3,4]]";
$ar = json_decode($json);
print_r($ar);
Which results in:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
)
If you want to decode it in JavaScript, you have a couple options. First, if your environment is new enough (e.g. this list), then you can use the native JSON.parse
function. If not, then you should use a library like json2.js to parse the JSON.
Assuming JSON.parse
is available to you:
var inputJSON = "[[1,2],[3,4]]",
parsedJSON = JSON.parse(inputJSON);
alert(parsedJSON[0][0]); // 1
Upvotes: 1