Node.js-将字符串解析为JSON对象

时间:2019-02-19 08:06:58

标签: node.js json parsing fs

我正在尝试在nodejs中使用fs.readFile和fs.read获取示例json文件。 这是我正在读取的json测试文件

{
    "HttpTestResponse":
        [
          { 
             "title":"testTitle2",
             "id": 2,
             "name":"testName3",
             "testArray":[{"testProp1":"testPropVal2","testProp2":"testPropVal_2"}]
          },
          {
            "title":"testTitle3",
            "id": 3,
            "name":"testName3",
            "testArray":[{"testProp1":"testPropVal3","testProp2":"testPropVal_3"}]
          }
        ]


}

这是示例函数(我正在使用带有Node.js的Typescript进行更严格的键入)

getJSONFromFile(paramId) {
    let obj: HttpTestModel[];
    fs.exists(this.resolvedUrl, exists => {
      if (exists) {
        fs.readFile(this.resolvedUrl, 'utf-8', (err, data) => {
          if (err) {
            this.pino.info('error while reading the file', err);
          } else {
            this.pino.info('data', JSON.parse(data));
            // tslint:disable-next-line:one-variable-per-declaration
            // tslint:disable-next-line:prefer-const
            // tslint:disable-next-line:one-variable-per-declaration
            obj = JSON.parse(data);
            this.pino.info('plain data', data);
            this.pino.info('data in parseJSON', parseJson(data));
          }
        });
      }
    });
  }

这是我得到的输出。我正在使用Pino模块,因此输出具有一些默认级别和时间戳

{"level":30,"time":1550563397320,"msg":"plain data {\r\n    \"HttpTestResponse\":\r\n        [\r\n
{ \r\n             \"title\":\"testTitle2\",\r\n             \"id\": 2,\r\n             \"name\":\"testName3\",\r\n             \"testArray\":[{\"testProp1\":\"testPropVal2\",\"testProp2\":\"testPropVal_2\"}]\r\n
      },\r\n          {\r\n            \"title\":\"testTitle3\",\r\n            \"id\": 3,\r\n            \"name\":\"testName3\",\r\n            \"testArray\":[{\"testProp1\":\"testPropVal3\",\"testProp2\":\"testPropVal_3\"}]\r\n          }\r\n        ]\r\n        \r\n    \r\n}","pid":21212,"hostname":"INDV072294","v":1}


{"level":30,"time":1550563397321,"msg":"stringifed data {\r\n    \"HttpTestResponse\":\r\n        [\r\n
     { \r\n             \"title\":\"testTitle2\",\r\n             \"id\": 2,\r\n             \"name\":\"testName3\",\r\n             \"testArray\":[{\"testProp1\":\"testPropVal2\",\"testProp2\":\"testPropVal_2\"}]\r\n          },\r\n          {\r\n            \"title\":\"testTitle3\",\r\n            \"id\": 3,\r\n
   \"name\":\"testName3\",\r\n            \"testArray\":[{\"testProp1\":\"testPropVal3\",\"testProp2\":\"testPropVal_3\"}]\r\n          }\r\n        ]\r\n        \r\n    \r\n}","pid":21212,"hostname":"INDV072294","v":1}


{"level":30,"time":1550563397322,"msg":"data in parseJSON {\"HttpTestResponse\":[{\"title\":\"testTitle2\",\"id\":2,\"name\":\"testName3\",\"testArray\":[{\"testProp1\":\"testPropVal2\",\"testProp2\":\"testPropVal_2\"}]},{\"title\":\"testTitle3\",\"id\":3,\"name\":\"testName3\",\"testArray\":[{\"testProp1\":\"testPropVal3\",\"testProp2\":\"testPropVal_3\"}]}]}","pid":21212,"hostname":"INDV072294","v":1}

我也尝试使用parse-json模块,但是没有什么可以帮助我实现所需的输出。我希望将JSON对象作为输出而不是字符串,因此可以对其进行存储和迭代,并过滤出所需的结果

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以使用pino-pretty,它是Pino的插件或模块。

npm i -S pino pino-pretty

示例代码如下:

const pino = require('pino')
const logger = pino({
    prettyPrint: {
        levelFirst: true,
    },
})
const filePath = '' // 

fs.exists(filePath, exists => {
    if (exists) {
        fs.readFile(filePath, 'utf-8', (err, data) => {
            if (err) {
            } else {
                const obj = JSON.parse(data);
                logger.info('data', JSON.parse(data));
                logger.info(JSON.parse(data));
                logger.info(data);
            }
        });
    }
});

记录器输出

INFO  [1550565533231] (19285 on aa-pc): data {"HttpTestResponse":[{"title":"testTitle2","id":2,"name":"testName3","testArray":[{"testProp1":"testPropVal2","testProp2":"testPropVal_2"}]},{"title":"testTitle3","id":3,"name":"testName3","testArray":[{"testProp1":"testPropVal3","testProp2":"testPropVal_3"}]}]}


INFO  [1550565533233] (19285 on aa-pc):
    HttpTestResponse: [
      {
        "title": "testTitle2",
        "id": 2,
        "name": "testName3",
        "testArray": [
          {
            "testProp1": "testPropVal2",
            "testProp2": "testPropVal_2"
          }
        ]
      },
      {
        "title": "testTitle3",
        "id": 3,
        "name": "testName3",
        "testArray": [
          {
            "testProp1": "testPropVal3",
            "testProp2": "testPropVal_3"
          }
        ]
      }
    ]

INFO  [1550565533234] (19285 on aa-pc): {
"HttpTestResponse":
[
{
"title":"testTitle2",
"id": 2,
"name":"testName3",
"testArray":[{"testProp1":"testPropVal2","testProp2":"testPropVal_2"}]
},
{
"title":"testTitle3",
"id": 3,
"name":"testName3",
"testArray":[{"testProp1":"testPropVal3","testProp2":"testPropVal_3"}]
}
]

}


您可以自己尝试。哈哈哈

答案 1 :(得分:0)

以上答案非常适合使用js的用户。如果您打算使用ts,则可以进行一些修改和最佳实践。

首先安装类型(pino的类类型定义)。

  

npm install -S @ types / pino

然后像上面一样安装小提琴

现在创建一个名为logger.ts的单独文件,并以这种方式导出pino的prertyprint配置

import * as pino from 'pino';

export const logger = pino({
  name: 'prj-sample',
  prettyPrint: {
    levelFirst: true,
  },
});

现在您可以像这样在代码中的任何位置导入记录器const并使用它

import { logger } from './../../../shared/utils/logger';
.....
.....
.....
getJSONFromFile(paramId) {
    let obj;
    fs.exists(this.resolvedUrl, exists => {
      if (exists) {
        fs.readFile(this.resolvedUrl, 'utf-8', (err, data) => {
          if (err) {
            logger.info('error while reading the file', err);
          } else {
            obj = JSON.parse(data);
            logger.info('data data :', obj.HttpTestResponse);
            logger.info('data is', JSON.parse(data));
            logger.info(JSON.parse(data));
            logger.info(data);
          }
        });
      }
    });
  }