I have a javascript file that has an object I’d like to be read by Python (Python 3 is just fine). Something like this:
let variable_i_do_not_want = 'foo' let function_i_do_not_wnt = function() { } // .. etc .. // --- begin object I want --- myObject = { var1: 'value-1', var2: 'value-2', fn2: function() { "I don't need functions.." }, mySubObject: { var3: 'value-3', .. etc .. } } // --- end object I want --- // .. more stuff I don't want ..
I want to convert myObject
to a python dict object. Note I don’t really need the functions, just keys and values.
I’m fine with (and capable) adding comment markers before/after and isolating the object. But I think I need a library to convert that string into a Python dict. Is this possible?
Advertisement
Answer
Doing this using python would be a lot of work that can be avoided if you could add a few things directly in your javascript file. (as you told you could modify the js file)
I assume that you have nodejs and npm preinstalled (if not then you can install it from here
You need to add these lines of code at the end of the JS file.
const fs = require("fs"); const getVals = (obj) => { let myData = {}; for (const key in obj) { if ( !(typeof obj[key] === "function") && // ignore functions (!(typeof obj[key] == "object") || Array.isArray(obj[key])) // ignore objects (except arrays) ) { myData[key] = obj[key]; } else if (typeof obj[key] === "object") { // if it's an object, recurse myData = { ...myData, ...getVals(obj[key]), }; } } return myData; }; // storing the data into a json file fs.writeFile( "myjsonfile.json", JSON.stringify(JSON.stringify(getVals(myObject))), //change your variable name here instead of myObject (if needed) (err) => { if (err) throw err; console.log("complete"); } );
once you add this you can run the js file by
~$ npm init -y ~$ node yourjsfile.js
This will make a new file named myjsonfile.json with the data which you can load from python like this
import json with open('myjsonfile.json') as file: d=json.loads(file.read()) #your dict print(d)
😉