Skip to content Skip to sidebar Skip to footer

Parsing - Json - Array Of Arrays

A JSON array has the form: [[a,b,c],[a,b,c],[a,b,c]] Is there a better way than split?

Solution 1:

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

Solution 2:

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

Solution 3:

In JavaScript , I think you can use Eval() → eval() method...

Post a Comment for "Parsing - Json - Array Of Arrays"