简体   繁体   中英

Parse Array-like string as Array

I have this JavaScript string that contains and array of malformed JSON and I would like to parse it as the array it represents. The string goes:

variable = [{ var1: 'value11', var12: 'value2', var3: 'value13' }, { var1: 'value21', var2: 'value22', var3: 'value23' }]

Is it possible to parse this so that it becomes an actual array?

I'm assuming that variable = is also returned as part of the string, so correct me if I'm wrong.

If you're using JavaScript, you can eval that, and then use it. Unfortunately this does mean that you're stuck with that variable name though.

http://jsfiddle.net/2xTmh/

If you're using php, you could "fix" the json string with regular expressions. This works:

<?php 
$json = "variable = [{ var1: 'value11', var12: 'value2', var3: 'value13' }, { var1: 'value21', var2: 'value22', var3: 'value23' }]";
// replace 'variable =' with '"variable" :' and surround with curly braces
$json = preg_replace('/^(\S+)\s*=\s*([\s\S]*)$/', '{ "\1" : \2 }', $json);
// quote keys and change to double quotes
$json = preg_replace("/(\S+): '(\S+)'/", '"\1": "\2"', $json);
echo $json . "\n";

$data = json_decode($json, true);

print_r($data);
?>

This outputs:

{ "variable" : [{ "var1": "value11", "var12": "value2", "var3": "value13" }, { "var1": "value21", "var2": "value22", "var3": "value23" }] }
Array
(
    [variable] => Array
        (
            [0] => Array
                (
                    [var1] => value11
                    [var12] => value2
                    [var3] => value13
                )

            [1] => Array
                (
                    [var1] => value21
                    [var2] => value22
                    [var3] => value23
                )

        )

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM