简体   繁体   中英

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

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

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