How can I convert the python class str to dictionary in javascript

272 Views Asked by At

I have a data in python that is in this format

 d1 = ["id":"hajdgrwe2123", "name":"john law", "age":"95"]

Python has it as data type " class 'str' ".

I am sending the data from python to javascript using eel so I want to convert the data to dictionary in javascript so that I can make the call below

d1["id"] # result should be hajdgrwe2123

I tried converting to json in javascript but it did not work. How can I convert the python class str to dictionary in javascript?

2

There are 2 best solutions below

0
domenikk On

When sending from Python to JS, you need to encode the data as JSON (using json.dumps() for example).

Then, you can parse it to a JS object using:

const d1 = JSON.parse(json_data);

You can access it's properties using:

d1['id'] // prints: hajdgrwe2123

or:

d1.id // prints: hajdgrwe2123
0
Attila Viniczai On

You can use json.dumps() function to convert a Python object to a JSON object string:

import json

d1 = {"id":"hajdgrwe2123", "name":"john law", "age":"95"}

json_str = json.dumps(d1)

# json_str = '{"id": "hajdgrwe2123", "name": "john law", "age": "95"}'
# Do something with json_str to pass it to the Javascript process

The JSON object can then be used as suggested by domenikk https://stackoverflow.com/a/64424921/14349691.