【发布时间】:2020-10-11 17:30:24
【问题描述】:
我一直在尝试理解和掌握使用 javascript 创建 json 对象,但是我似乎无法弄清楚如何(首先迭代某些内容,然后使用该值作为我的键)。我的第二个问题是当我看到我的 json 结果时,它似乎总是与前面的空白项嵌套在一起。这就是我的意思:
我当前的代码部分是:
.then((data)=>{
connection.query("SELECT * FROM amion_onCall", function (err, result, fields){
const fixed = [];
let i;
for (i in result){
aName = result[i].name;
aServ = result[i].specialty;
aShift = result[i].shift;
aOff = result[i].office;
aCell = result[i].cell;
aTag = result[i].tag;
var data = {aServ: {name:aName, service: aServ, shift: aShift, office: aOff, cell: aCell, tag: aTag}};
// console.log(data);
fixed.push(data);
}
fs.writeFile('./data/json/newAmion.json', JSON.stringify(fixed), function(err){
if (err) throw err;
console.log("Wrote New Amion");
});
});
})
我的 json 查看器中的输出是:
[
{
"aServ": {
"name": "Dr.John",
"service": "Cardiology",
"shift": "7a-7p",
"office": "123",
"cell": "123-456-789",
"tag": "no tags"
}
},
...对于我的大约 150 个条目,依此类推。
问题#1:我想将它提升一整级。我不知道该怎么做,也不知道为什么它开始嵌套如此之深。
问题 #2: 当我迭代 aServ 时,我希望在我的 json 开头输出实际值。我当前的代码为每个人静态打印“aServ”……我不想那样做。例如,这就是我试图让我的 json 输出的方式:
{
"Cardiology": {
"name": "Dr.John",
"service": "Cardiology",
"shift": "7a-7p",
"office": "123",
"cell": "123-456-789",
"tag": "no tags"
},
"Pulmonology": { ...and so on
}
【问题讨论】:
标签: javascript json properties iteration key