Home > Mobile >  How to export python variable as javascript file
How to export python variable as javascript file

Time:05-15

I have a python variable in jupyter notebook

allFolders = {'1': { '2': {'3': { 'A' : {}, 'B' : {}, 'C': {}}}}}

I am wondering if there is a way to export this variable as a javascript file? What I currently have is:

file = open('allFolders.js','w')
file.write(allFolders)
file.close

Which does create a javascript file. However, does my python variable 'allFolders' need to be converted to JSON before this to be valid? My end goal is to import my 'allFolders.js' file into a 'directory.js' file so that 'directory.js' may use the contents of 'allFolders.js' as a const.

const {allFolders} = require('./allFolders.js');

But this doesn't seem to work. What steps am I missing here? I am very new to Javascript/JSON.

CodePudding user response:

Since your all-folders variable is a nested dictionary, why not export it as a JSON instead of a js file. If you won't have any additional functionality like functions or additional variables inside your 'Allfolders.js' file and only hold the dictionary object, Then it's better if you export it as a JSON file and add/import the dictionary object/JSON value to a variable inside 'directory.js' file

CodePudding user response:

You can't write a dict object to the file. Try this

import json

file = open('allFolders.js', 'w')
file.write(json.dumps([allFolders]))
file.close

Passing allFolders dict as a list encloses it in square brackets essentially making it an JSON object.

  • Related