4

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;
}
TonyW
  • 18,375
  • 42
  • 110
  • 183
  • By the way what you are showing there is not "a JSON object". That is a javascript object. JSON (by definition) is a string representation of javascript objects and in it's default implementation (before you try to rewrite it) it produces a single line string. – gforce301 Apr 10 '18 at 22:06
  • 3
    interesting .. a question that has the answer in the title – Slai Apr 10 '18 at 22:09

1 Answers1

20

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);
Simon Wicki
  • 4,029
  • 4
  • 22
  • 25
  • silly me, I first tried `JSON.stringify`, but it gave me multiple lines of string, which made me painstakingly reinvent the wheel. lol. thank you thank you :) – TonyW Apr 10 '18 at 22:09
  • 4
    @TonyGW The third argument to `stringify` controls how the string is displayed with newlines and spaces. – Sebastian Simon Apr 10 '18 at 22:18