วิธีการ prettify JSON.stringify () บางส่วน

Oct 01 2020

ผู้ใช้สามารถดาวน์โหลดไฟล์ JSON จากแอปพลิเคชันของเราซึ่งฉันต้องการกำหนดค่าล่วงหน้าเพื่อการดีบักที่ง่ายกว่าถ้าทั้งหมดอยู่ในบรรทัดเดียว อย่างไรก็ตามสิ่งนี้จะเพิ่มขนาดไฟล์ขึ้นเกือบ 40% แม้ว่าการเยื้องจะเป็นเพียงแท็บเดียวหรือช่องว่างก็ตาม

ในการประนีประนอมฉันต้องการยกเว้นค่าทั้งหมดที่มีเช่นคีย์ "ใหญ่" จากการระบุไว้ล่วงหน้าเช่นนี้:

{
 "small":
 {
  "a": 1,
  "b": 2,
  "large": {"a":1,"b":2,"c":3,"d":"the \"large\" object should not be prettified"} 
 },
  "large": {"a":1,"b":2,"c":3,"d":"the \"large\" object should not be prettified"}
}

ฉันพยายามแก้ปัญหานี้โดยใช้พารามิเตอร์ replacer ของ JSON.stringify:

JSON.stringify(data,(key,value)=>key==="large"?JSON.stringify(data):value,'\t');

อย่างไรก็ตามค่าของคีย์ "large" จะมีค่า Escape:

data = 
{
     "small":
     {
      "a": 1,
      "b": [2,3,4,5],
      "large": {"myarray":[1,2,3,4],"b":2,"c":3,"d":"the \"large\" object should not be prettified"} 
     },
      "large": {"a":1,"b":2,"c":3,"d":"the \"large\" object should not be prettified"}
    }
    
 const json =  JSON.stringify(data,(key,value)=>key==="large"?JSON.stringify(data):value,'\t');
 document.getElementById("json").innerText = json;
<html>
<body>
<pre id="json">
</pre>
</body>
</html>

ฉันจะป้องกันไม่ให้สิ่งนี้เกิดขึ้นได้อย่างไรหรือทำให้ JSON บางส่วนเตรียมไว้ล่วงหน้าใน JavaScript

คำตอบ

2 sbgib Oct 06 2020 at 16:00

ทุกครั้งที่คุณเรียกJSON.stringifyใช้วัตถุ (หรือบางส่วนของวัตถุ) มากกว่าหนึ่งครั้งคุณจะได้รับเครื่องหมายคำพูดที่ใช้ Escape ในกรณีนี้หลังจากใช้JSON.stringifyฟังก์ชันด้านในภายในฟังก์ชันตัวเปลี่ยนแล้วไม่มีวิธีใดที่จะบอกให้JSON.stringifyฟังก์ชันภายนอกไม่ปฏิบัติต่ออินสแตนซ์นั้นเหมือนกับสตริงอื่น ๆ

ดังนั้นฉันคิดว่าถ้าเป้าหมายของคุณคือ 'บางส่วน' ทำให้วัตถุมีความซับซ้อนคุณต้องเขียนฟังก์ชันที่ใช้งานสิ่งนั้น สำหรับปัญหานี้ฉันขอแนะนำสิ่งนี้:

data = {
  "small": {
    "a": 1,
    "b": [2, 3, 4, 5],
    "c": [2, {"test":"example"}, [4,4], 5],
    "large": {
      "myarray": [1, 2, 3, 4],
      "b": 2,
      "c": 3,
      "d": "the \"large\" object should not be prettified"
    }
  },
  "large": {
    "a": 1,
    "b": 2,
    "c": 3,
    "d": "the \"large\" object should not be prettified"
  }
}

function print(obj, exclude, space) {
  let recur = (obj, spacing, inarray) => {
    let txt = '';

    if (inarray) {
      if (Array.isArray(obj)) {        
        txt += '[';

        for(let i=0;i<obj.length;i++) {
          txt += recur(obj[i], spacing + space, true);
        };

        txt = txt.substr(0, Math.max(1,txt.length - 2)) + ']';
        
      } else if (typeof obj === 'object' && obj !== null) {
        txt += '{' + recur(obj, spacing + space, false) + '\n' + spacing + '}';
      } else if (typeof obj === 'string') {
        txt += obj.replaceAll(/\"/g, '\\"') + '"';
      } else {
        txt += obj;
      };
      
      return txt + ', ';
      
    } else {
      for (let key of Object.keys(obj)) {
        if (exclude.indexOf(key) !== -1) {
          txt += '\n' + spacing + '"' + key + '": ' + JSON.stringify(obj[key]);
        } else if (Array.isArray(obj[key])) {
          txt += '\n' + spacing + '"' + key + '": [';
          
          for(let i=0;i<obj[key].length;i++) {
            txt += recur(obj[key][i], spacing + space, true);
          };
          
          txt = txt.substr(0, Math.max(1,txt.length - 2)) + ']';
          
        } else if (typeof obj[key] === 'object' && obj[key] !== null) {
          txt += '\n' + spacing + '"' + key + '": {' + recur(obj[key], spacing + space, false) + '\n' + spacing + '}';
        } else if (typeof obj[key] === 'string') {
          txt += '\n' + spacing + '"' + key + '": "' + obj[key].replaceAll(/\"/g, '\\"') + '"';
        } else {
          txt += '\n' + spacing + '"' + key + '": ' + obj[key];
        };
        
        txt += ',';
      };
      
      return txt.substr(0, txt.length - 1);
    };

  };
  return (Array.isArray(obj) ? '[' + recur(obj, space, true) + '\n' + ']' : '{' + recur(obj, space, false) + '\n' + '}');
};

document.getElementById("json").innerText = print(data, ['large'], '\t');
<html>
<body>
  <pre id="json">
</pre>
</body>
</html>

ในที่นี้จะมีการใช้ฟังก์ชันแบบวนซ้ำซึ่งจะวนลูปผ่านคีย์ของออบเจ็กต์และต่อท้ายคู่คีย์ - ค่าเข้ากับสตริงเพื่อจัดการข้อมูลประเภทต่างๆ หากkeyพบในexcludeอาร์เรย์แสดงว่าเป็นสตริง

ด้วยการวนซ้ำคีย์และใช้ตามเงื่อนไขJSON.stringifyเมื่อจำเป็นคุณจะหลีกเลี่ยงปัญหาข้างต้นได้อย่างมีประสิทธิภาพ

ฉันแน่ใจว่าอาจมีกรณีขอบที่ต้องระวังเมื่อเขียน JSON ด้วยตัวเองแทนที่จะใช้ฟังก์ชันในตัว แต่คุณสามารถปรับเปลี่ยนสิ่งนี้ให้เหมาะกับความต้องการเฉพาะของคุณได้

แก้ไข: อัปเดตคำตอบเพื่อให้พิจารณาอาร์เรย์ภายในวัตถุได้ดีขึ้น