0

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?

Haroldo_OK
  • 6,612
  • 3
  • 43
  • 80
e.iluf
  • 1,389
  • 5
  • 27
  • 69
  • 2
    `d1 = {"id":"hajdgrwe2123", "name":"john law", "age":"95"}` is the correct format. Doesn't seem like a JS question to me, more like a python + JSON one. – MauriceNino Oct 19 '20 at 09:49

2 Answers2

1

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
domenikk
  • 1,723
  • 1
  • 10
  • 12
1

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.

Attila Viniczai
  • 644
  • 2
  • 8