Rivka
Rivka

Reputation: 843

Parsing php array in python

I'm getting a PHP array from a web page (as a string). It looks like :

Array
(
[k1] => Array
    (
        [a] => Array
            (
                [id] => 1
                [age] => 60
            )

        [b] => Array
            (
                [id] => 2
                [age] => 30
            )

    )

[k2] => v2
)

I want to parse it in python. Does anyone have an idea how to do this?

Thanks, Rivka

Edit: This is really not a json, like a few people commented. Thanks for the comments, and I updated the question.

Upvotes: 3

Views: 2315

Answers (2)

XzKto
XzKto

Reputation: 2502

If I understood you correctly, you are using print_r on array to get that output. This is a visual representation of array only, you can't really parse it. For example:

array('Array'.PHP_EOL."\t(".PHP_EOL."            [0] => test".PHP_EOL."\t)")

will look exactly like

array(array('test'));

You should use some real serializing function to do what you want(json,serialize etc.);

Upvotes: 4

rcapote
rcapote

Reputation: 1044

That's not JSON, that's just how PHP prints arrays. If you want to create JSON of the array, check out json_encode for PHP. Then use Python's JSON library (or here for py3) to read it.

Upvotes: 10

Related Questions