简体   繁体   中英

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
}

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'}

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.

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