How to convert Javascript dictionary to Python dictionary?


Python and javascript both have different representations for a dictionary. So you need an intermediate representation in order to pass data between them. The most commonly used intermediate representation is JSON, which is a simple lightweight data-interchange format.

Example

The dumps function converts the dict to a string. For example,

import json
my_dict = {
   'foo': 42,
   'bar': {
      'baz': "Hello",
      'poo': 124.2
   }
}
my_json = json.dumps(my_dict)
print(my_json)

Output

This will give the output:

'{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}'

Example

The load's function converts the string back to a dict. For example,

import json
my_str = '{"foo": 42, "bar": {"baz": "Hello", "poo": 124.2}}'
my_dict = json.loads(my_str)
print(my_dict['bar']['baz'])

Output

This will give the output:

Hello

On the JS side of things, you don't need to do anything. This is because JSON literally means JavaScript Object Notation. And JS implicitly constructs objects from JSON. If you get a string, you can convert it using JSON.parse().

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 17-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements