1

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?

5
  • 1
    What programming language are you using? Commented May 7, 2012 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. Commented May 7, 2012 at 16:10
  • Sorry, forgot to mention that. It's been added to the OP just in case. Commented May 7, 2012 at 20:39
  • Why is the "JSON" malformed at all? Commented May 8, 2012 at 13:07
  • It comes from coding I have no authority over. I can only work with it. Commented May 8, 2012 at 14:31

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I don't mind sticking with that variable name, it's not an issue. You're a lifesaver.
1

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
                )

        )

)

1 Comment

Thanks and yes, php would make it easier... unfortunately it's not an option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.