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
}
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
}
Share
Improve this question
edited Sep 24, 2020 at 16:00
Aditya Yada
asked Sep 24, 2020 at 15:38
Aditya YadaAditya Yada
1662 gold badges2 silver badges10 bronze badges
2
|
3 Answers
Reset to default 11You 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.
What you're asking for is actually a format called "json5".
https://json5.org/
Install and use the json5 npm package.
{ type: 'Fiat', model: '500', color: 'White' }
is valid JSON. It is a valid JS object, though not sure about JSON, that's whystringify
doesn't produce it. – sjahan Commented Sep 24, 2020 at 15:41