Search code examples
javascriptjsonstringify

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;
}

Solution

  • 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);