admin管理员组

文章数量:1332737

Is it possible to remove the quotes from keys in JSON.stringify? Normally it will have quotes:

const object = { name: "Foo Bar", birthdate: { date: "2000-01-01", time: "12:34" } };
console.log(JSON.stringify(object, null, "    "));

Is it possible to remove the quotes from keys in JSON.stringify? Normally it will have quotes:

const object = { name: "Foo Bar", birthdate: { date: "2000-01-01", time: "12:34" } };
console.log(JSON.stringify(object, null, "    "));

Output:

{
    "name": "Foo Bar",
    "birthdate": {
        "date": "2000-01-01",
        "time": "12:34"
    }
}

What I want is something like this:

{
    name: "Foo Bar",
    birthdate: {
        date: "2000-01-01",
        time: "12:34"
    }
}

Is this even possible, or do I have to create my own JSON serializer?

Share Improve this question asked Feb 7, 2021 at 18:23 blaumeise20blaumeise20 2,22011 silver badges26 bronze badges 6
  • 1 A JSON object is supposed to have the quotes. If you remove them, that would not be a valid JSON – clod9353 Commented Feb 7, 2021 at 18:25
  • JSON names require double quotes. JavaScript names do not. So on doing JSON stringyfy it es without quotes. – Tanmay Shrivastava Commented Feb 7, 2021 at 18:30
  • 1 I've used the below NPM package to achieve this. npmjs./package/stringify-object – Madhav Appaneni Commented Feb 7, 2021 at 18:31
  • What if a property name has a colon? – trincot Commented Feb 7, 2021 at 18:34
  • Needed this too in a specific application. I found this code what works for me to not use double quotes around the keys. demo2s./javascript/… – A.W. Commented Mar 16, 2022 at 14:44
 |  Show 1 more ment

3 Answers 3

Reset to default 2

It sounds like you are looking for a data-serialization format that is human-readable and version-control-friendly but not as strict about quotes as JSON.

Such formats include:

  • Relaxed JSON (RJSON) (simple keys and simple values generally do not require quotes)
  • Hjson (simple keys and simple values generally do not require quotes)
  • YAML (keys and values generally do not require quotes)
  • JavaScript object literal (also printed out by many implementations of "console.dir()" when passed a JavaScript object; simple keys generally not required to be quoted, but string values must be quoted by either single quotes or double quotes)

for pleteness:

JSON (requires double-quotes around keys, also called property names, and requires double-quotes around string data values).

Yes, it is possible to remove the quotes from the keys. Doing so will render it invalid as JSON, but still valid when used directly in JavaScript code, only if the keys you use are also valid variable names. When you paste a JSON object in JavaScript code, it may be useful to have the quotes removed, as they can in some cases take up a lot of data. If that's relevant to your project, then this is the answer for you.

The function below works for any JavaScript variable and works fine with objects/arrays containing objects/arrays. I've added ments to explain what's going on. Please note that this code does not check for possible reserved keywords that may not be allowed as JavaScript keys, such as "for".

function toUnquotedJSON(param){ // Implemented by Frostbolt Games 2022
    if(Array.isArray(param)){ // In case of an array, recursively call our function on each element.
        let results = [];
        for(let elem of param){
            results.push(toUnquotedJSON(elem));
        }
        return "[" + results.join(",") + "]";
    }
    else if(typeof param === "object"){ // In case of an object, loop over its keys and only add quotes around keys that aren't valid JavaScript variable names. Recursively call our function on each value.
        let props = Object
            .keys(param)
            .map(function(key){
                // A valid JavaScript variable name starts with a dollar sign (?), underscore (_) or letter (a-zA-Z), followed by zero or more dollar signs, underscores or alphanumeric (a-zA-Z\d) characters.
                if(key.match(/^[a-zA-Z_$][a-zA-Z\d_$]*$/) === null) // If the key isn't a valid JavaScript variable name, we need to add quotes.
                    return `"${key}":${toUnquotedJSON(param[key])}`;
                else
                    return `${key}:${toUnquotedJSON(param[key])}`;
            })
            .join(",");
        return `{${props}}`;
    }
    else{ // For every other value, simply use the native JSON.stringify() function.
        return JSON.stringify(param);
    }
}

A JSON string is a string type basically, a mon language that Servers understand, that's why we need to send JSON to the Servers for further processing. What you are trying to get is an object in javascript.

But you already have that object to work with.

const object = { name: "Foo Bar", birthdate: { date: "2000-01-01", time: "12:34" } };

本文标签: javascriptJSONstringify key without quotesStack Overflow