Bill N Bill N - 2 months ago 12x
JSON Question

In JavaScript code how to get data from a Python JSON variable

The following code in Python:

jsVar = (json.dumps(jsPass))

produces this output:

"TT1004": [
[1004, 45.296109039999997, -75.926546579999993,
66.996664760000002, 150, false
"TT1001": [
[1001, 45.296471220000001, -75.923881289999997, 64.616423409999996, 150, false]
"TT1003": [
[1003, 45.296109379999997, -75.926543379999998,
67.240025419999995, 150, false
"TT1002": [
[1002, 45.29626098, -75.924908610000003, 65.300880480000004, 150, true]

The output passes validation on the JSON Formatter & Validator website.

In the JavaScript code I’ve set the following:

var myVar2 = {};
var myVar2 = jsVar;

When I look at the output of the
methods for the JavaScript variable
, there is no data. It returns
Object { }
along with an empty

In order to test that the Python data that is generated is correct JS, I have manually placed the data into the JavaScript variable which logs the following:

TT1004: Array[1],
TT1001: Array[1],
TT1003: Array[1],
TT1002: Array[1]

What I need to learn is how to import the Python JSON jsVar variable into the JavaScript Code.


From your original post:

Python: jsVar = (json.dumps(jsPass))

JavaScript code: var myVar2 = jsVar;

Q: How to access Python JSON variable from Javascript code?

A: Python and Javascript are two different languages and you would run them differently, for instance to run Python code you normally use the python binary and to execute Javascript you would use a JS engine like Google's V8.

Note that: When you run your python and javascript code, that is essentially taken care by 2 different processes. That is, they will have different memory space hence it is not possible for your Javascript process to access memory space of your Python code, unless we are talking about Unix's shared memory. (I won't bother touching on this)

So if you are thinking about directly accessing a variable from 1 language or even process to another process then it is NOT possible.

However, keep in mind that a variable is just a reference to your content. What I'm trying to say is - you don't need the variable to be ported across, rather you need the content.

The easiest method for a newbie would be to serialize (layman term: save) the content to a File and then have the Javascript process read out the content and parse it back into an object.

I hope these guides will be useful to you;

Python side:
For writing JSON data to a File using Python - you can refer to this SO post for solution.
How do I write JSON data to a file in Python?

Javascript side:
For reading JSON data back out from a file you can easily do this through NodeJS.
Using Node.JS, how do I read a JSON object into (server) memory?