简体   繁体   中英

TypeScript : convert JSON in Array of some type

I've read a lot of posts around here, but I still can't make it works. Can anyone point what I am doing wrong ?

I'm using TypeScript 3.7.5 (tsconfig)

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ]
  }
}

I've got a JSON file :

{
  "result" : [ {
    "line" : 1,
    "dateTime" : "2020-01-15T00:00:06.338",
    "thread" : "main",
    "logLevel" : "INFO",
    "description" : "by (com.xxx.xxx.batch.consumer.EventConsumer:280)  sleep Consumer PAY_REQ_CONSUMER - Waiting for a message ... [main]"
  }, {
    "line" : 2,
    "dateTime" : "2020-01-15T00:00:13.350",
    "thread" : "main",
    "logLevel" : "INFO",
    "description" : "by (com.xxx.xx.batch.consumer.EventConsumer:280)  sleep Consumer PAY_REQ_CONSUMER - Waiting for a message ... [main]"
  }, {...

I want to map every objects contained in this file with an object of my own : LogLine

export default class LogLine {

    constructor(public line: number,
    public dateTime: Date,
    public thread: String,
    public logLevel: String,
    public description: String) { }

}

I've got a class for importing datas :

import LogLine from './log-line';

export default class JsonImporter {
    constructor() { }

    import() {

        const fileContent = require('../src/LogsFilesStore/scf-finance-consumer1.json');
        const xx = JSON.parse(fileContent);
        console.log(xx[0]);
        return fileContent;
    }

}

Here's what I see in the console :

{ result:
   [ { line: 1,
       dateTime: '2020-01-15T00:00:06.338',
       thread: 'main',
       logLevel: 'INFO',
       description:
        'by (com.xxx.xx.batch.consumer.EventConsumer:280)  sleep Consumer PAY_REQ_CONSUMER - Waiting for a message ... [main]' },
     { line: 2,
       dateTime: '2020-01-15T00:00:13.350',
       thread: 'main',
       logLevel: 'INFO',
       description:
        'by (com.xxx.xx.batch.consumer.EventConsumer:280)  sleep Consumer PAY_REQ_CONSUMER - Waiting for a message ... [main]' },
     ...

I've tried many ways in order to map all of this to a LogLine[] array, but I always have error messages if I try to do something like this : const fileContent: LogLine[] = data.result;

For example :

"result is not a property of {}"

More elements on error :

> typescript-log-charter@1.0.0 import C:\Users\Loveg\Workspaces\MyEclipse CI\LogCharter
> ts-node src/launch.ts


C:\Users\Loveg\Workspaces\MyEclipse CI\LogCharter\src\import-datas.ts:9
                const xx = JSON.parse(fileContent);
                  ^
SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)
    at JsonImporter.import (C:\Users\Loveg\Workspaces\MyEclipse CI\LogCharter\src\import-datas.ts:9:19)
    at Object.<anonymous> (C:\Users\Loveg\Workspaces\MyEclipse CI\LogCharter\src\launch.ts:4:28)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Module.m._compile (C:\Users\Loveg\Workspaces\MyEclipse CI\LogCharter\node_modules\ts-node\src\index.ts:400:23)
    at Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Object.require.extensions.(anonymous function) [as .ts] (C:\Users\Loveg\Workspaces\MyEclipse CI\LogCharter\node_modules\ts-node\src\index.ts:403:12)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)

Thanx by advance.

You need to parse your json first. Try something like this:

export default class JsonImporter {
    constructor() { }

    import() {
        const fileContent = JSON.parse(data);
        return fileContent.result.map(c => new LogLine(c.line, c.dateTime, c.thread, c.logLevel, c.description));
    }
}

When you call console.log on a json object, it will strip the outermost \\"\\" so it seems like it is an object, but it is basically a string, so you need to parse it first for it to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM