簡體   English   中英

在 JavaScript 中格式化 JSON 對象

[英]Format JSON object in JavaScript

我有一個 JSON 對象,其鍵和值的格式不同。 我想將其格式化為正確的 JSON 格式。 PFB JSON 數據

我想在json下面轉換

  {
              \"abc\": \"test\",
              \"xyz\": \"test1\",
              \"array\": [
                  {
                      \"path\": [\"test\"],
                      \"output\": {}
                  }
              ]
    } 

格式如下

 {
            "abc": "test",
            "xyz": "test1",
            "array": [
                {
                    "path": ["test"],
                    "output": {}
                }
            ]
   }

我從數據庫中獲取了這個 JSON,我需要將其轉換為有效的 JSON。

我不知道如何格式化這個 JSON。 是否有任何正則表達式可以格式化整個 JSON 對象?

 var data = `{ \\"abc\\": \\"test\\", \\"xyz\\": \\"test1\\", \\"array\\": [ { \\"path\\": [\\"test\\"], \\"output\\": {} } ] }`; console.log(JSON.parse(data));

如果您將此數據作為字符串獲取 - 只需執行以下操作:

JSON.stringify(JSON.parse(data))

答案只是為了以防萬一,當您的字符串帶有轉義" ,如果還有其他一些符號, JSON.parse可能會拋出錯誤。

實際上JSON.parse對於該字符串就足夠了

const data = '{\"abc\": \"test\",\"xyz\": \"test1\",\"array\":[{ \"path\":[\"test\"],\"output\":{}}]}';


var jsondata = JSON.parse(data);
console.log('jsondata: ', jsondata);

var regex = data.replace(/\\/g, '');
console.log('regex: ', regex);

是的,你可以使用這個正則表達式: \\\\"並通過替換捕獲結果" 如果變量data json 無效,您可以使用以下代碼:

data.replace(/\\"/g,'"');

這是正則表達式示例: https : //regex101.com/r/qUV7St/1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM