【问题标题】:How can print out a list with json?如何用json打印出一个列表?
【发布时间】:2019-11-03 22:24:21
【问题描述】:

我需要将 json 中的内容作为列表打印出来,如下所示:

{
  "attendees": [
    "Kevin Tyler",
    "Syeda Shyra",
         ]
}

但截至目前,我有:

{
    "attendees": [
        {
            "attendee": "Kevin Tyler"
        },
        {
            "attendee": "Syeda Shyra"
        }
    ]
}

我用这个打印出来:

res.json({attendees: response.rows});

我的数据库如下:

  attendee   |      workshop      
-------------+--------------------
 Ann Nowicki | React Fundamentals
 Ann Nowicki | TensorFlo
 Kevin Tyler | Biology 101
 Syeda Shyra | Biology 101

我怎样才能使它不列出每个人的与会者,而是在开始时只说一次与会者?

如果你需要,这里有更多我的代码:

 30 app.get("/api", async (req,res) => {
 31 
 32 
 33         try {
 34                 // if there is an argument
 35                 // else there isn't
 36 
 37                 // find attendee
 38                 const template = "SELECT attendee FROM people WHERE workshop =$1";
 39                 const response = await pool.query(template, [req.query.workshop]);
 40 
 41                 console.log(response);
 42                 // can print
 43                 if (req.query.workshop!=null) {
 44                         if (response.rowCount!=0) {
 45                                   res.json({attendees: response.rows});
 46                          } else {
 47                                 res.json({"error": "workshop not found"});
 48                         }
 49 
 50                 } else {
 51                         const resp = await pool.query("SELECT workshop FROM people");
 52                         res.json({workshops: resp.rows});
 53                 }
 54 
 55 
 56         } catch (err) {
 57                 console.error("whoops " + err);
 58                 res.json({status:"error"});
 59         }
 60 
 61 
 62 });

【问题讨论】:

标签: javascript json get


【解决方案1】:

您需要解开每个row 的内容。使用map 函数来实现。 Docs.

res.json({attendees: response.rows.map(a=>a.attendee)});

【讨论】:

    猜你喜欢
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 2022-12-18
    • 2017-09-30
    • 1970-01-01
    • 2015-11-03
    相关资源
    最近更新 更多