Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
leyendo el objeto JavaScript en un archivo en una matriz de Python

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.js

Esto 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)

;)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!