Estoy tratando de analizar el resultado de mi llamada de python con JSON.parse . Proporciono aquí solo el resultado de mi script de python (el diccionario).
secuencia de comandos de pitón
import json mydict = { "brand": "Ford", "model": "Mustang", "licensePlate" : "O XXX YYY", "year" : 1964, "insured": { 'lastname' : 'Snow', 'firstname' : 'John', 'adress' : 'Holiday street, 4 - Paradise' } } myjsonlist = json.dumps(mydict, indent = 4) print(myjsonlist) mi javascript llama al script de python e intenta analizar el resultado (= el diccionario de python). El objetivo es poder utilizar este diccionario en javascript. En otras palabras, me gustaría extraer en javascript la marca del automóvil como brandCar = resut.brand .
//Import express.js module and create its variable. const express=require('express'); const app=express(); //Import PythonShell module. const {PythonShell} =require('python-shell'); //Router to handle the incoming request. //Here are the option object in which arguments can be passed for the python_test.js. let options = { mode: 'text', pythonOptions: ['-u'], // get print results in real-time scriptPath: '/mnt/c/Users/xxxxx/javascript/' //If you are having python script in same folder, then it's optional. //args: ['xxxx'] //An argument which can be accessed in the script using sys.argv[1] }; PythonShell.run('pythonscript.py', options, function (err, result){ if (err) throw err; // result is an array consisting of messages collected //during execution of script. console.log('result: ', result.toString()); console.log(JSON.parse(result[0])); });En la consola, tengo esto como mensaje de error y resultado.
result: {, "brand": "Ford",, "model": "Mustang",, "licensePlate": "O XXX YYY",, "year": 1964,, "insured": {, "lastname": "Snow",, "firstname": "John",, "adress": "Holiday street, 4 - Paradise", },} undefined:1 { SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at /mnt/c/Users/xxxxx/javascript/test2.js:62:19 at PythonShell._endCallback (/mnt/c/Users/xxxxx/javascript/node_modules/python-shell/index.js:254:20) at terminateIfNeeded (/mnt/c/Users/xxxxx/javascript/node_modules/python-shell/index.js:209:39) at ChildProcess.<anonymous> (/mnt/c/Users/xxxxx/javascript/node_modules/python-shell/index.js:182:13) at ChildProcess.emit (events.js:400:28) at Process.ChildProcess._handle.onexit (internal/child_process.js:282:12)¿Me puede ayudar con esto? Trabajo con Ubuntu Bash para Windows 10, no sé si esta información es relevante o no...
Finalmente resolví mi problema por
1) en el script de python, imprimo el diccionario sin convertirlo en un objeto json. Cuando se llama a python en javascript, devuelve una cadena como la siguiente
result: {'brand': 'Ford', 'model': 'Mustang', 'licensePlate': 'O XXX YYY', 'year': 1964, 'insured': {'lastname': 'Snow', 'firstname': 'John', 'adress': 'Holiday street, 4 - Paradise'}}
esta cadena contiene comillas simples.
2) En javascript, reemplazo todas las comillas simples con comillas dobles para analizar esta cadena en un objeto json.
let parsedData = JSON.parse(JSON.stringify(result.join('\n'))); parsedData = parsedData.replace(/'/g, `"`); // replace the quote by the double quotes for parsing the string to a JSON object. parsedData = JSON.parse(parsedData);