繁体   English   中英

如何将 JSONObject 转换为 JSONArray?

[英]How to convert JSONObject to a JSONArray?

最近在Android APP中尝试实现评论功能时遇到了这个问题。

user.js 中注释的定义如下

comnents: [{

    ownerID: {
        type: String,
        required: true,

    },
    commenterID: {
        type: String,
        required: true,

    },
    commenterName: String,
    content: {
        type: String,
        require: true,

    }
}],

我有一个这样的要求:

{
    "_id":"60d204d6efc6c70022b08dc4",
    "comments":[
        {
            "ownerID":"60d204d6efc6c70022b08dc4",
            "commenterID":"60d205afefc6c70022b08dc8",
            "commenterName":"Bob",
            "content":"Hello World!"
        },
        {
            "ownerID":"60d204d6efc6c70022b08dc4",
            "commenterID":"60d20892efc6c70022b08dd2",
            "commenterName":"Alice",
            "content":"Hello Earth!"
        }
    ]
}

这是我的 API

router.post("/writecomment",jsonParser,
    async(req,res,next)=>{
        const errors=validationResult(req);
        if(!errors.isEmpty()){
            return res.status(400).json({erros:errors.array()});
        }
        
        User.findOneAndUpdate(
            { "_id": req.body._id},
            {
                $set: {
                    comments:req.body.comments
                }
            },
            {overwrite:true},
            function(err,resp){
                if(err) throw err;
                if(resp) {
                    return res.send({
                        msg:' change successfully'
                    });
                }else{
                    return res.status(403).json({ success: false, message: 'Failed to change'});
                }
            }
          )


    }
)

如何将“评论”从请求转换为评论数组? 或者有更好的方法来实现这个功能?

PS:我使用Mongoose + Express Framework 来开发。

const commentArray = [...req.body.comments]

会为你做这个:

[
    {
        "ownerID": "60d204d6efc6c70022b08dc4",
        "commenterID": "60d205afefc6c70022b08dc8",
        "commenterName": "Bob",
        "content": "Hello World!"
    },
    {
        "ownerID": "60d204d6efc6c70022b08dc4",
        "commenterID": "60d20892efc6c70022b08dd2",
        "commenterName": "Alice",
        "content": "Hello Earth!"
    }
]

基本上这里发生的事情是,我们正在迭代您得到的响应并将结果保存在一个数组中。 如果您想了解有关...运算符的更多信息,请查看此链接: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM