Estoy tratando de escribir un archivo JSON que contiene palabras coincidentes de un texto como este
servicepoint 200135644 watchid 7038842por lo tanto, cada punto de servicio y watchid se insertarán en la tabla de objetos solo una vez usando este código:
function readfile() { Tesseract.recognize('form.png', 'ara', { logger: m => console.log(m) }).then(({ data: { text } }) => { console.log(text); /* this line here */ var obj = { table: [] }; const info = ['servicepoint', 'watchid']; for (k = 0; k < info.length; k++) { var result = text.match(new RegExp(info[k] + '\\s+(\\w+)'))[1]; obj.table.push({ servicepoint: /* Here i want to insert the number after servicepoint*/ , watchid: /*also i want to insert the number after watchid to the Object table*/ }); } var json = JSON.stringify(obj); /* converting the object table to json file*/ var fs = require('fs'); /* and then write json file contians the data*/ fs.writeFile('myjsonfile.json', json, 'utf8', callback); }) };De uno de mis comentarios anteriores...
Incluso se podría quitar el indicador u nicode y traducir el patrón anterior de nuevo a
/servicepoint\W+(\w+)/que está bastante cerca del código original del OP. El OP solo necesita cambiar el\\s+por un\\W+
Además del cambio de patrón propuesto, también cambiaría los elementos del OP en tareas más claras, como separar la lectura de archivos del análisis/extracción de datos de json-conversion/write .
También quiero afirmar que el formato basado en la data.table de datos deseado del OP no puede ser una matriz, sino que debe ser una estructura (objeto) de clave-valor pura, ya que uno puede agregar un solo objeto (una entrada a la vez mientras se itera la propiedad nombres) o inserte elementos de propiedad única (un elemento a la vez mientras se iteran los nombres de propiedad) en una matriz. (El OP intenta crear un objeto de entrada múltiple aunque también lo empuja).
El siguiente código provisto muestra el enfoque. La implementación sigue el código original del OP. Simplemente usa la sintaxis async-await y simula/falsifica los procesos de lectura y escritura de archivos.
async function readFile(fileName) { console.log({ fileName }); // return await Tesseract.recognize(fileName, 'ara', { // // logger: m => console.log(m) // }); // fake it ... return (await new Promise(resolve => setTimeout( resolve, 1500, { data: { text: 'servicepoint 200135644 watchid 7038842'} } ) )); } /*async */function parseDataFromTextAndPropertyNames(text, propertyNames) { console.log({ text, propertyNames }); return propertyNames .reduce((table, key) => Object.assign(table, { [ key ]: RegExp(`${ key }\\W+(\\w+)`) .exec(text)?.[1] ?? '' }), {}); } async function writeParsedTextDataAsJSON(fileName, table) { console.log({ table }); // const fs = require('fs'); // fs.writeFile(fileName, JSON.stringify({ table }), 'utf8', callback); // fake it ... return (await new Promise(resolve => setTimeout(() => { console.log({ fileName, json: JSON.stringify({ table }) }); resolve({ success: true }); }, 1500) )); } console.log('... running ...'); (async () => { const { data: { text } } = await readFile('form.png'); const data = /*await*/ parseDataFromTextAndPropertyNames(text, ['servicepoint', 'watchid']); const result = await writeParsedTextDataAsJSON('myjsonfile.json', data); console.log({ result }); })(); .as-console-wrapper { min-height: 100%!important; top: 0; }Puede usar String.match para obtener los valores de variable requeridos para sus dos claves: "punto de servicio" y "watchid".
Sugeriría usar este patrón de coincidencia para obtener sus dos puntos de datos.
Luego, deberá crear y luego codificar el JSON, lo que le dará algo como: {servicepoint: 1323, watchid: 234}
Supongo que tiene muchas de estas filas, por lo que querrá agregar cada valor clave JSON a una matriz. Luego puede JSON.stringify(dataArray) para generar el texto JSON válido para escribir en un archivo.