Com convertir TXT a JSON amb C#

Com convertir TXT a JSON amb C#

Converting text files to JSON is useful when integrating legacy or structured flat-file data into modern APIs or data pipelines. With Aspose.Cells for .NET, you can seamlessly convert .txt files to .json format using a few simple lines of C# code.

Per què convertir TXT a JSON?

  • Compatibilitat de l’aplicaci:- JSON és un format estàndard per a sistemes web i backend, fet que és ideal per a la transferència de dades.

  • Resultats estructurats:- Convertir el text brut en JSON estructurat per facilitar la manipulació i la lectura.

  • Automatitzaci:- Elimina les tasques de conversió manual amb lògica C# programable.

Guia de pas a pas per convertir TXT a JSON

Pas 1: Instal·lar Aspose.Cells a través de NuGet

Afegeix la biblioteca Aspose.Cells al teu projecte .NET:

dotnet add package Aspose.Cells

Pas 2: Configure la llicència

Permeten les característiques autoritzades:

Metered matered = new Metered();
matered.SetMeteredKey("PublicKey", "PrivateKey");

Pas 3: Carregar el fitxer TXT

Initialize a Workbook and load the input .txt file:

Workbook workbook = new Workbook("sampleTxt.txt");

Pas 4: Set JsonSaveOptions

Crear un exemple per gestionar com s’emmagatzemen les dades:

JsonSaveOptions options = new JsonSaveOptions();

Pas 5: Exportació a JSON

Convertir el contingut del llibre de treball en format JSON:

workbook.Save("output.json", options);

Pas 6: Salvar la sortida de JSON

The output is saved as a .json file on disk.

Pas 7: Personalitzar la sortida (opcional)

Use JsonSaveOptions to fine-tune export options such as:

  • Classificació de claus
  • Instal·lació de titulacions
  • Escapant rutes buides o fulles

Problemes comuns i fixos

Format de fitxers TXT

  • Solució: Assegureu-vos que el fitxer TXT està estructurat amb delimitors consistents (per exemple, taules o commas) per ajudar a pars.

Resultats buits o parcials

  • Solution: Use JsonSaveOptions to ensure appropriate rows and columns are selected for export.

Errors d’accés al fitxer

  • Solució: comprova els camins de fitxer i les autoritzacions en carregar o guardar fitxers.
 Català