简体   繁体   English

验证并将 JavaScript object 格式化为 JSON 格式

[英]Validate and format a JavaScript object to a JSON format

I have to send a given javascript object from angular to backend(nestJS),我必须将给定的 javascript object 从 angular 发送到后端(nestJS),

{
      service: {
        port: 3080,
      },
      datasource: {
        m3: {
          rest: {
            url: 'https://se/',
            username: 'di.com',
            password: 'B4',
          },
        },
        postgraphile: {
          url: 'https://gl',
          hostname: 'sg',
          port: 1133,
          database: 'MV',
          username: 'rr',
          password: '1',
        },
      },
      database: {
        pg: {
          hostname: 'ss.com',
          port: 5432,
          username: 'br',
          password: '1x',
          database: 'eb',
          synchronize: false,
        },
        mssql: {
          hostname: '10.100.100.100',
          port: 1133,
          database: 'MV',
          schema: 'MA',
          username: 'rr',
          password: 'we',
        },
        redis: {
          url: 'redis:///0',
        },
      },
      graphql: {
        playground: true,
      },
    }

I tried to make this a JSON object in order to send the data,我试图将其设为 JSON object 以便发送数据,

var objKeysRegex = /({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g;// look for object names
var newQuotedKeysString = b.replace(objKeysRegex, "$1\"$2\":");// all object names should be double quoted
console.log(newQuotedKeysString);

I got the expected outcome but unable to make it a proper JSON string, due to trailing commas which there is no value after some commas.我得到了预期的结果,但无法使其成为正确的 JSON 字符串,因为尾随逗号在一些逗号之后没有任何价值。 The output I got was:我得到的 output 是:

{"service": {"port": 3080,
      },"datasource": {"m3": {"rest": {"url": "https://se/","username": "di.com","password": "B4",
          },
        },"postgraphile": {"url": "https://gl","hostname": "sg","port": 1133,"database": "MV","username": "rr","password": "1",
        },
      },"database": {"pg": {"hostname": "ss.com","port": 5432,"username": "br","password": "1x","database": "eb","synchronize": false,
        },"mssql": {"hostname": "10.100.100.100","port": 1133,"database": "MV","schema": "MA","username": "rr","password": "we",
        },"redis": {"url": "redis:///0",
        },
      },"graphql": {"playground": true,
      },
    }

Is there any other way apart from this, or any idea about making it a valid JSON format.除此之外还有其他方法吗,或者关于使其成为有效 JSON 格式的任何想法。

To convert a JavaScript object to a JSON string, do:要将 JavaScript object 转换为 JSON 字符串,请执行以下操作:

let str = JSON.stringify(obj);

First we need to Get the JavaScript Object (Nested Object) and surround the key values in the object with double quotes "" and validate for trailing commas.首先,我们需要获取 JavaScript Object(嵌套对象)并将 object 中的键值用双引号 "" 括起来,并验证尾随逗号。

For that,为了那个原因,

//replace '' with "".
let confJsonvalue = obj.replace(/'/g, '"');

//replace trailling comma
let regex = /\,(?=\s*?[\}\]])/g;
let sanitized = confJsonvalue.replace(regex, '');

let objKeysRegex =/({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g; // look for object names
let newQuotedKeysString = sanitized.replace(objKeysRegex, '$1"$2":'); // all object names/Keys should be double quoted.

JSON.parse(newQuotedKeysString);

Using JSON.stringify(obj);使用JSON.stringify(obj); will only surround the object with double quotes and return a string.只会用双引号将 object 括起来并返回一个字符串。 (for nested JavaScript objects this is not enough). (对于嵌套的 JavaScript 个对象,这还不够)。

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

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