How can I convert Python dictionary to JavaScript hash table?

PythonProgramming

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.

The dumps function converts the dict to a string. 

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. 

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().

raja
Published on 19-Apr-2018 10:40:56
Advertisements