Tengo un archivo javascript que tiene un objeto que me gustaría que Python lea (Python 3 está bien). Algo como esto:
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 .. Quiero convertir myObject en un objeto dict de Python. Tenga en cuenta que realmente no necesito las funciones, solo claves y valores.
Estoy bien con (y puedo) agregar marcadores de comentarios antes/después y aislar el objeto. Pero creo que necesito una biblioteca para convertir esa cadena en un dictado de Python. es posible?
Hacer esto usando python sería mucho trabajo que se puede evitar si pudiera agregar algunas cosas directamente en su archivo javascript. (como dijiste que podrías modificar el archivo js)
Supongo que tiene nodejs y npm preinstalados (si no, puede instalarlo desde aquí )
Debe agregar estas líneas de código al final del archivo JS.
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"); } );una vez que agregue esto, puede ejecutar el archivo js por
~$ npm init -y ~$ node yourjsfile.jsEsto creará un nuevo archivo llamado myjsonfile.json con los datos que puede cargar desde python como este
import json with open('myjsonfile.json') as file: d=json.loads(file.read()) #your dict print(d);)