【问题标题】:TypeScript : convert JSON in Array of some typeTypeScript:将 JSON 转换为某种类型的数组
【发布时间】:2020-05-29 14:01:38
【问题描述】:

我在这里阅读了很多帖子,但我仍然无法使其正常工作。 谁能指出我做错了什么?

我正在使用 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"
    ]
  }
}

我有一个 JSON 文件:

{
  "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]"
  }, {...

我想用我自己的对象映射这个文件中包含的每个对象:LogLine

export default class LogLine {

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

}

我有一个导入数据的类:

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;
    }

}

这是我在控制台中看到的:

{ 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]' },
     ...

为了将所有这些映射到 LogLine[] 数组,我尝试了很多方法,但如果我尝试做这样的事情,我总是会收到错误消息:const fileContent: LogLine[] = data.result;

例如:

“结果不是 {} 的属性”

更多关于错误的元素:

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

提前致谢。

【问题讨论】:

    标签: arrays json typescript import


    【解决方案1】:

    你需要先解析你的 json。试试这样的:

    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));
        }
    }
    

    当你在一个json对象上调用console.log时,它会去掉最外层的\"\",所以看起来它是一个对象,但它基本上是一个字符串,所以你需要先解析它才能工作.

    【讨论】:

    • Thanx @kaca992 不幸的是,这是我尝试过的事情的一部分。这是我收到的错误消息:“'{}' 类型的参数不可分配给 'string' 类型的参数。”
    • 你的 tsconfig.json 中有 "resolveJsonModule": true 吗?
    猜你喜欢
    • 2020-10-29
    • 1970-01-01
    • 2020-11-09
    • 2019-12-15
    • 2019-02-09
    • 2023-02-05
    • 1970-01-01
    • 2021-11-04
    • 2019-03-23
    相关资源
    最近更新 更多