我在nodejs中尝试使用fs.read file和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"}]
}
]
}
这是示例函数(我使用typescript和nodejs进行更严格的输入)
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对象作为输出,而不是字符串,这样我就可以存储它并迭代它并过滤出所需的结果
有人能帮我解决这个问题吗?