简体   繁体   English

JSON.stringify() 在值上带有单引号,键上没有引号

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

In Javascript: print a json object在 Javascript 中:打印一个 json 对象

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

in below format以下格式

{ type: 'Fiat', model: '500', color: 'White' } { 类型:'菲亚特',型号:'500',颜色:'白色'}

in console.log .在 console.log 中。

But actual result但实际结果

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

Challenge is here :挑战在这里:

hackerrank print JSON object hackerrank 打印 JSON 对象

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 JSON.stringify() 值上没有单引号,键上没有引号

You can't.你不能。 By-design.按设计。

The JSON specification requires all properties' names to be enclosed in double-quotes and parsed as JSON strings: JSON 规范要求所有属性的名称用双引号括起来并解析为 JSON 字符串:

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 4. 对象

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.单个逗号将值与以下名称分开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM