4

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
}
Ali Hesari
  • 1,821
  • 5
  • 25
  • 51

2 Answers2

4

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.
wonton
  • 7,568
  • 9
  • 56
  • 93
3

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

nathan hayfield
  • 2,627
  • 1
  • 17
  • 28