0

I have this piece of code responsible to query a database and output the information as JSON format:

connectionpool.getConnection(function(err, connection) {
    if (err) {
        console.error('CONNECTION error: ',err);
        res.statusCode = 503;
        res.send({
            result: 'error',
            err: err.code
        });
    } else {
        connection.query(query, function(err, rows) {
            if (err) {
                console.error(err);
                res.statusCode = 500;
                res.send({
                    result: 'error',
                    err: err.code
                });
            } else {
                res.send({
                    json: rows
                });
            }
            connection.release();
        });
    }
});

The output is the following:

{"json":[{"id":39937,"transcript_alias":"AC148152.3_FGT007","expression":0,"tissue":"Leaf","conditions":"No-stress"},{"id":39941,"transcript_alias":"AC155352.2_FGT012","expression":0.217,"tissue":"Leaf","conditions":"No-stress"}]}

but I'd like to have this output:

{"json":[
    {"id":39937,
      "transcript_alias":"AC148152.3_FGT007",
      "expression":0,
      "tissue":"Leaf",
      "conditions":"No-stress"},
    {"id":39941,
     "transcript_alias":"AC155352.2_FGT012",
     "expression":0.217,
     "tissue":"Leaf",
     "conditions":"No-stress"
    }
]}

with break lines, making it more visible and understandable. Is that possible?

2

1 Answer 1

1

Looking into MDN Documentation

JSON.stringify(value[, replacer [, space]])

You can see that there is a third parameter to stringify function, called space wich causes the resulting string to be pretty-printed.

You can use a tab character mimics standard pretty-print appearance:

JSON.stringify({ first: 1, second: 2 }, null, '\t')
// returns the string:
// '{           
//     "first": 1,
//     "second": 2
// }'
Sign up to request clarification or add additional context in comments.

6 Comments

It does not work when writing in my code res.send(JSON.stringify(rows, null, '\t')); instead of res.send({json: rows});...
The extra whitespaces means nothing different to the machine... it only matters to a human that needs to understand it. you only want to pretty print it when you actually have a person that needs to look at it
huh? I meant It is printed without tabs and nothing is formatted doing res.send(JSON.stringify(rows, null, '\t'));
How do you print it ?
I'm working with NodeJS, the way NodeJS send information to your browser is doing res.send. Again, doing res.send(JSON.stringify(rows, null, '\t')); it does not print anything formatted.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.