Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

Thanks in advanced.

share|improve this question
1  
What programming language are you using? – Asaph May 7 '12 at 16:09
1  
The solution to this is going to be extremely dependent on what language you plan to use. Please edit your question to explain that. – pjmorse May 7 '12 at 16:10
Sorry, forgot to mention that. It's been added to the OP just in case. – Paco Giurfa Ley May 7 '12 at 20:39
Why is the "JSON" malformed at all? – Bergi May 8 '12 at 13:07
It comes from coding I have no authority over. I can only work with it. – Paco Giurfa Ley May 8 '12 at 14:31

2 Answers

up vote 2 down vote accepted

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/

share|improve this answer
Thank you! I don't mind sticking with that variable name, it's not an issue. You're a lifesaver. – Paco Giurfa Ley May 7 '12 at 19:22

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
                )

        )

)
share|improve this answer
Thanks and yes, php would make it easier... unfortunately it's not an option. – Paco Giurfa Ley May 7 '12 at 19:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.