Home > Blockchain >  How to send json result as a Dictionary instead of Array in expressjs
How to send json result as a Dictionary instead of Array in expressjs

Time:09-17

I want to send response as a dictionary like this:

{
    "id": 5928101,
    "category": "animal welfare",
    "organizer": "Adam",
    "title": "Cat Cabaret",
    "description": "Yay felines!",
    "location": "Meow Town",
    "date": "2019-01-03T21:54:00.000Z",
    "time": "2:00",
}

But I am using bellow code, which results an array

var ress = JSON.stringify(sqlResults)
console.log('response json:'   ress)
res.send(ress)

The resulted array has brackets [] like this:

[
    {
        "id": 5928101,
        "category": "animal welfare",
        "organizer": "Adam",
        "title": "Cat Cabaret",
        "description": "Yay felines!",
        "location": "Meow Town",
        "date": "2019-01-03T21:54:00.000Z",
        "time": "2:00",
    }
]

How can I send result without a third bracket?

CodePudding user response:

If you return the first element of your sqlResults array you should get the result you wish.

You should also be able to use res.json(dict) to send your result to the client.

sqlResults = [
    {
        "id": 5928101,
        "category": "animal welfare",
        "organizer": "Adam",
        "title": "Cat Cabaret",
        "description": "Yay felines!",
        "location": "Meow Town",
        "date": "2019-01-03T21:54:00.000Z",
        "time": "2:00",
    }
];

const dict = sqlResults[0];
var ress = JSON.stringify(dict, null, 2)
console.log('response json:'   ress)

// You can then send using res.send(ress);
// Or simply res.json(dict);

  • Related