简体   繁体   中英

Parse json object to string in node.js

this my code

app.get('/status',function ( req,res) {
        var data = {
            "error": 1,
            'data status': ""
        };
        connection.query("SELECT * from status", function (err, rows, fields) {
            if (rows.length != 0) {
            data = rows;
                console.log(data);
                res.json(data);
             } else {
                data["Data status"] = '0';
                res.json(data);
            }
        })
});

I had a problem I try to change the json object

[{"id_status":5,"pin_arduino":1,"status":0}] 

I will eliminate be

{"id_status":5,"pin_arduino":1,"status":0}

It's not clear what you're asking for.

If you get this:

[{"id_status":5,"pin_arduino":1,"status":0}]

and you want this:

{"id_status":5,"pin_arduino":1,"status":0}

then instead of:

res.json(data);

use:

res.json(data[0]);

If you get this:

{"id_status":5,"pin_arduino":1,"status":0}

and you want this:

[{"id_status":5,"pin_arduino":1,"status":0}]

then instead of:

res.json(data);

use:

res.json([data]);

Also, looking at your examples, this:

data["Data status"] = '0';

should probably be:

data.status = 0;

or:

data[0].status = 0;

depending on how your data really looks like, which is not entirely clear from your question.

Note that you're not doing anything with JSON here. You just handle normal JS objects which get serialized to JSON automatically by Express when you use res.json() so there's no need to use JSON.parse() or JSON.stringify() at all, at least not in the code that you included in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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