Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript JSON stringify: make it output a one-line compact string

I'm trying to create a custom function for converting a JSON object to a one-line string. For example:

var obj = {
 "name": "John Doe",
 "age": 29,
 "location": "Denver Colorado",
};

I would like to make it output: "{ \"name\": \"John Doe\", \"age\": 29, \"location\": \"Denver Colorado,\"}"

My function below does not work, which makes me wonder how to remove the new lines (hidden) in the output:

function objToCompactString(obj) {
        var result = "\"{";
        Object.keys(obj).forEach(key => {
            result += `"${key}":"${obj[key]}",`;
        });

        result += "}\"";
        return result;
}
like image 817
TonyGW Avatar asked Jul 11 '26 13:07

TonyGW


1 Answers

You may want to have a look at JSON.stringify.

In your case:

var obj = {
    "name": "John Doe",
    "age": 29,
    "location": "Denver Colorado",
};
var result = JSON.stringify(obj);
console.log(result);
like image 97
Simon Wicki Avatar answered Jul 14 '26 14:07

Simon Wicki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!