提问人:steveS 提问时间:11/14/2023 最后编辑:steveS 更新时间:11/17/2023 访问量:44
读取json文件并仅打印特定行
Read json file & print only specific rows
问:
我有下面的json数据文件,想做以下事情:
- 读取json文件并检查行数(此操作已完成)
- 我已经设置了 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赞
Adesoji Alu
11/14/2023
#1
从我所看到的,我认为要在 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));
}
评论
jsonData.splice(0, maxRowCount)
stringify