10

If I have the object literal:

{a: "hello"}

Is there a Javascript function to convert this object into a literal string, so that the output would be the literal syntax:

'{a: "hello"}'

With JSON.stringify the output would be

'{"a": "hello"}'
7
  • 1
    One problem is that once the object exists, it's not possible to know how identifier-like property names were expressed when the object was created (or subsequent properties added). They may or may not have had quotes. Commented Jan 29, 2019 at 19:38
  • 1
    Unsure what your objective is, but you could (mis)use JSON.stringify()... Commented Jan 29, 2019 at 19:39
  • Maybe this can help stackoverflow.com/a/5612876/3565132 Commented Jan 29, 2019 at 19:40
  • 2
    Just to be clear, though, {"a":"hello"} is a legal literal object representation, so I'm not sure why the JSON representation isn't sufficient for your purpose. Commented Jan 29, 2019 at 19:41
  • 4
    Fixing the server so it supports JSON instead of a non-standard data format would be a better bet. Commented Jan 29, 2019 at 19:58

4 Answers 4

7

You can do it with JSON.stringify and then with String.replace like follows:

var jsObj =
{
    abc: "hello",
    bca: "allo",
    cab: "dd:cc",
    d: ["hello", "llo", "dd:cc"],
    e: {abc: "hello", bca: "allo", cab: "dd:cc"}
};

function format(obj)
{
    var str = JSON.stringify(obj, 0, 4),
        arr = str.match(/".*?":/g);

    for(var i = 0; i < arr.length; i++)
        str = str.replace(arr[i], arr[i].replace(/"/g,''));

    return str;
}

console.log(format(jsObj));

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Brahata it just took me some time to check the responses but I appreciate your effort and it helped me a lot. In the end I understand that I shouldn't pass JSON objects to the server like that because it's prone to bugs, but I did learn how to make manipulations on string from your and other's answers. Thanks!
@sir-haver, thank you for your response! You can find on my account site a lot of good answers. And here is the list of my answers especially in JavaScript.
this worked perfectly when sending form fields from React to the backend with Graphql :)
3

JavaScript has no built-in functions that will convert an object to a string representation of it which either:

  • Uses identifiers instead of strings for property names
  • Represents the original syntax used to create the object

You could write your own function for the former (at least when the property name can be represented as a literal) but the latter is impossible as JavaScript stores no information about the source code used to create the object in the first place.

1 Comment

Thanks a lot mate
1

Ok just for fun...roll your own?

const stringify = (obj) => {
    // Iterate over keys, reducing to a string
    let str = Object.keys(obj).reduce((acc, cur) => {
        let next = `${cur}: "${obj[cur]}"`;
        return acc
            ? `${acc}, ${next}`
            : `{${next}`;
    }, '');
    
    // Return, appending final '}'
    return `${str}}`;
}

document.write(stringify({
    foo:1,
    bar:'seat'
}));

That said, your exact requirements aren't clear so I'm not sure this will meet them. But it might be a starting point if there's no native solution that works.

1 Comment

@jonaswilms it could easily be modified to support nested objects and arrays. Since the requirements weren’t complete I provided, as mentioned, a starting point that demonstrates a concept.
0

It does convert it to the literal syntax. You are able to create objects with multiple forms of syntax. Both of the following object declarations are valid:

var a = {a: "a"}
var b = {"b": "b"}

If you want to remove the "" around the key you should be able to match them with the following regex /\"(.*?)\":/g and replace them with something like this:

function reformat(str) {
    var myRegexp = /\"(.*?)\":/g;
    match = myRegexp.exec(str);
    while (match != null) {
        str = str.replace(match[0], match[1] + ":");
        match = myRegexp.exec(str);
    }

    return str;
}

Hope that helps :)

1 Comment

Thanks a lot mate

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.