Thijs
Thijs

Reputation: 71

How to convert javascript array to a python dictionary

I want to try to make a little webserver where you can put location data into a database using a grid system in Javascript. I've found a setup that I really liked and maked an example in CodePen: https://codepen.io/anon/pen/XGxEaj. A user can click in a grid to point out the location. In the console log I see the data that is generated as output. For every cell in the grid it has a dictionary that looks like this:

click: 4
height: 50
width: 50
x: 1
xnum: 1
y: 1
ynum: 1

A complete overview of output data looks like this, where their are 10 arrays for every row, 10 arrays for every column of that row, and then a dictionary with the values: enter image description here

Now i want to get this information back to python in a dictionary as well, so i can store particular information in a database. But I can't figure out what the best way is to do that. Hopefully you could provide a little push in the right direction, links to usefull pages or code snippets to guide me.

Thanks for any help in advance!

Upvotes: 2

Views: 1426

Answers (2)

Ulrich Dohou
Ulrich Dohou

Reputation: 1559

You should use the python json module.

Here is how you can perform such operation using the module.

import json
json_data = '{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}'
loaded_json = json.loads(json_data)

Upvotes: 1

Max Stevens
Max Stevens

Reputation: 111

This can be achieved by converting your JS object into JSON:

var json = JSON.stringify(myJsObj);

And then converting your Python object to JSON:

import json
myPythonObj = json.loads(json)

More information about the JSON package for Python can be found here and more information about converting JS objects to and from JSON can be found here

Upvotes: 2

Related Questions