我有下面的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"
}]
型
1条答案
按热度按时间lzfw57am1#
在我看来,我认为在Node.js中只打印JSON文件的前三行,你不需要用换行符分割JSON数据,因为JSON数据已经是一个对象数组。你可以直接访问这个数组的元素。尝试像这样重构你的代码以实现想要的输出
JavaScript
字符串