'How to export python variable as javascript file
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.
Solution 1:[1]
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.
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Geeky Quentin |
| Solution 2 | Freddy Mcloughlan |
