7

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;
}
2
  • 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. Commented Apr 10, 2018 at 22:06
  • 3
    interesting .. a question that has the answer in the title Commented Apr 10, 2018 at 22:09

1 Answer 1

22

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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 :)
@TonyGW The third argument to stringify controls how the string is displayed with newlines and spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.