JSON.stringify() with single quotes on value and no quotes on key

In Javascript: print a json object

var myObject = new Object;
myObject.type = "Fiat";
myObject.model = "500";
myObject.color = "White";

in below format

{ type: 'Fiat', model: '500', color: 'White' }

in console.log .

But actual result

{"type":"Fiat","model":"500","color":"White"}

Challenge is here :

hackerrank print JSON object

function printObjectProperty(myObject) {
  //Write your code here
console.log(JSON.stringify(myObject)); 
 //OR
console.log("{ type: '"+myObject.type+"', model: '"+myObject.model+"', color: '"+myObject.color+"'}"); //OR THERE COULD BE A BETTER GENERIC SOLUTION
}

2 answers

  • answered 2020-09-24 15:41 Dai

    JSON.stringify() without single quotes on value and no quotes on key

    You can't. By-design.

    The JSON specification requires all properties' names to be enclosed in double-quotes and parsed as JSON strings:

    1. Introduction

    [...]
    An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

    4. Objects

    An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name.

  • answered 2020-09-24 15:49 Top Talent

    You can use below code:

    var json = JSON.stringify(myObject);  // {"type":"Fiat","model":"500","color":"White"}
    console.log(json);
    var unquoted = json.replace(/"([^"]+)":/g, '$1:');
    console.log(unquoted);  // {type:"Fiat",model:"500",color:"White"}
    var result = unquoted.replaceAll("\"", "'");
    console.log(result); // {type:'Fiat',model:'500',color:'White'}