NodeJS 读取JSON文件并仅打印特定行

j8yoct9x  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(123)

我有下面的json数据文件,想做下面的事情:
1.读取json文件并检查行数(已完成)
1.我已经设置了maxRowCnt=2,所以我只需要从JSON文件中打印2行
示例Json文件:

[
  {
    "Name": "User1",
    "primaryRegion": "US"
  },
  {
    "Name": "user2",
    "primaryRegion": "US"
  },
  {
    "Name": "user3",
    "primaryRegion": "US"
  },
  {
    "Name": "user4",
    "primaryRegion": "US"
  },
  {
    "Name": "user5",
    "primaryRegion": "US"
  },
  {
    "Name": "user6",
    "primaryRegion": "US"
  },
  {
    "Name": "user7",
    "primaryRegion": "US"
  }
]

字符串

2我尝试打印json数据,但得到的数据如下:

Json Data---"[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]"


代码:

const fs = require("fs");

let jsonData = JSON.parse(fs.readFileSync('./test/sampleData1.json', 'utf8'));

console.log('Debug1---'+typeof(jsonData));

let jsonRowCount = jsonData.length;
let maxRowCount = 2;

console.log("JSON ROW COUNT Printed here---"+jsonRowCount);

let jsonData1 = jsonData.toString().split('\n');

console.log('Debug2---'+typeof(jsonData1));

for(let i=1; i <= maxRowCount; i++){
  
  console.log("i Value Print---"+i);

  console.log("Json Data---"+JSON.stringify(jsonData1);
  
}


输出应为:

[{
    "Name": "User1",
    "primaryRegion": "US"
  },
  {
    "Name": "user2",
    "primaryRegion": "US"
  }]

lzfw57am

lzfw57am1#

在我看来,我认为在Node.js中只打印JSON文件的前三行,你不需要用换行符分割JSON数据,因为JSON数据已经是一个对象数组。你可以直接访问这个数组的元素。尝试像这样重构你的代码以实现想要的输出
JavaScript

const fs = require('fs');

// Reading and parsing the JSON file
let jsonData = JSON.parse(fs.readFileSync('./test/sampleData1.json', 'utf8'));

// Define the maximum number of rows to print
let maxRowCount = 3;

console.log("JSON ROW COUNT Printed here---" + jsonData.length);

// Looping through the first maxRowCount elements of the JSON array
for (let i = 0; i < maxRowCount; i++) {
    console.log("Row " + (i + 1) + " Data---" + JSON.stringify(jsonData[i], null, 2));
}

字符串

相关问题