简体   繁体   中英

JSON.stringify key without quotes

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?

I've used the below NPM package to achieve this.

https://www.npmjs.com/package/stringify-object

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 completeness:

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 comments 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 common 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" } };

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