Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nested PHP Array to nested Python Dictionary

I have a PHP script and want to write that in Python. So, How can I convert this nested PHP Array to nested python dictionary?

$data = [
    'details'=> [
        [
          ['quick_event'=> 'Quick'], 
          ['advance_event'=> 'Advanced']
        ],
        [
          ['help'=> 'Help']
        ]
    ],
    'has_car'=> true,
    'has_payment'=> false
];

I created this in Python but it's wrong:

data = {
    'details': {
        {
          {'quick_event': 'Quick'}, 
          {'advance_event': 'Advanced'}
        },
        {
          {'help': 'Help'}
        }
    },
    'has_car': True,
    'has_payment': False
}
like image 432
Ali Hesari Avatar asked Mar 08 '23 03:03

Ali Hesari


2 Answers

This question is rather narrow but here we go:

data = {
    'details': [
        [
          {'quick_event': 'Quick'}, 
          {'advance_event': 'Advanced'}
        ],
        [
          {'help': 'Help'}
        ]
    ],
    'has_car': True,
    'has_payment': False
};
>>> data
{'details': [[{'quick_event': 'Quick'}, {'advance_event': 'Advanced'}], [{'help': 'Help'}]], 'has_car': True, 'has_payment': False}

In a nutshell:

  • Convert => to :
  • Convert [] to {} for maps.
like image 68
wonton Avatar answered Mar 17 '23 00:03

wonton


In php use http://php.net/manual/en/function.json-encode.php to format the data as json.

In python convert the json to a dictionary.

Maybe check this link to see how to convert json to dictionary in python: Converting JSON String to Dictionary Not List

like image 25
nathan hayfield Avatar answered Mar 17 '23 01:03

nathan hayfield