gpt4 book ai didi

json - 如何使用 node.js 访问 json 对象的子元素

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:39 25 4
gpt4 key购买 nike

在我的 node.js 应用程序中,我从 mongodb 服务器检索值,并希望将它们转换为 CSV 文件。父元素可以很容易地从数据库访问并显示在 CSV 文件中,但子元素不显示并且可以'无法访问..

JSON 结构:

"name" : "fhj",
"age" : "23",
"gender" : "female",
"sec" : "b",
"username" : "9886666",
"language" : "HINDI",
"method" : "method2",
"timeSlot" : {
"id" : 2,
"fromTime" : 12,
"toTime" : 15
}

我的代码:

db.users.find(function(err,values){
if(err||!values.length)
console.log("ERROR !!!!");
else
{
var i=1;
str='[';
values.forEach(function(user){
if(i==values.length)
str=str+'{ "name" : "' + user.username + '","age" : "'+ user.age +'","gender":"'+user.gender+'","sec":"'+user.sec+'","username":"'+user.username+'","language":"'+user.language+'","method":"'+user.method+'","Timeslot":"'+user.timeslot+'"}';
else{
str = str + '{ "name" : "' + user.username + '","age" : "'+ user.age +'","gender":"'+user.gender+'","sec":"'+user.sec+'","username":"'+user.username+'","language":"'+user.language+'","method":"'+user.method+'","Timeslot":"'+user.timeslot+'"},' +'\n';
i++;
}
});
str = str.trim();
str = str + ']';
var obj=JSON.parse(str);
json2csv({data: obj, fields: ['name', 'age','gender','sec','username','language','method','Timeslot']}, function(err, csv) {
if (err)
console.log(err);
fs.writeFile('./files/user.csv', csv, function(err) {
if (err)
throw err;
console.log('File saved');
});
});
}
});

显示除timeslot子元素外的所有值。如何从数据库访问 JSON 的子元素并在 CSV 文件中显示所有值???

最佳答案

可以在 following thread 的答案中找到访问嵌套元素的简单方法。 (访问嵌套数据结构)。

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation.

As we can see timeSlot is an object, hence we can access its properties using dot notation. The items property is accessed as follows:

timeSlot.id

Alternatively, we could have used bracket notation for any of the properties, especially if the name contained characters that would have made it invalid for dot notation usage:

var item_name = timeSlot['id'];

一旦您拥有所需的所有数据,CSV 文件的创建应该非常简单:)

关于json - 如何使用 node.js 访问 json 对象的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27355184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com