Amando Arkan
Amando Arkan

Reputation: 35

how to convert json array to object rest api on express

i tested rest api using postman and the result

{
    "success": true,
    "message": "success",
    "data": [
        {
            "id_buku": 9,
            "judul_buku": "xxxxxx",
        }
    ]
}

I want "data" : {...} but the result is "data" : [{...}]

i am using express node.js to develop rest api

getDataBukuByID(req,res){
    let id = req.params.id;
    pool.getConnection(function(err, connection) {
        if (err) throw err;
        connection.query(
            `
            SELECT * FROM buku WHERE id_buku = ?;
            `
        , [id],
        function (error, results) {
            if(error) throw error;

            res.send({
                success: true,
                message: 'success',
                data: results
            });
        });
        connection.release();
    })
},

what code should be changed?

Upvotes: 0

Views: 884

Answers (2)

S Ahmed Naim
S Ahmed Naim

Reputation: 304

res.send({
    success: true,
    message: 'success',
    data: results
});

On the data key, you have assigned the variable named results which is returning by the callback function. As it is returning as an array of objects, so this is why the final output on that property is returning as array of object. The result must be always array of objects if it returns one more collection of data. Otherwise return single row to get an specific object as well.
You can use LIMIT on your mysql query to fetch single data. Then just return that row as an object.

Upvotes: 1

Tony George
Tony George

Reputation: 126

hi bro actually what do you mean..? if you want value in an object you can use data.id_buku to get the value '9

Upvotes: 1

Related Questions