Converting an object to a string

后端 未结 30 1903
北荒
北荒 2020-11-22 03:29

How can I convert a JavaScript object into a string?

Example:

var o = {a:1, b:2}
console.log(o)
console.log(\'Item: \' + o)

Output:

30条回答
  •  一生所求
    2020-11-22 04:24

    Circular References

    By using below replacer we can produce less redundant JSON - if source object contains multi-references to some object, or contains circular references - then we reference it by special path-string (similar to JSONPath) - we use it as follows

    let s = JSON.stringify(obj, refReplacer());
    

    function refReplacer() {
      let m = new Map(), v= new Map(), init = null;
    
      return function(field, value) {
        let p= m.get(this) + (Array.isArray(this) ? `[${field}]` : '.' + field); 
        let isComplex= value===Object(value)
        
        if (isComplex) m.set(value, p);  
        
        let pp = v.get(value)||'';
        let path = p.replace(/undefined\.\.?/,'');
        let val = pp ? `#REF:${pp[0]=='[' ? '$':'$.'}${pp}` : value;
        
        !init ? (init=value) : (val===init ? val="#REF:$" : 0);
        if(!pp && isComplex) v.set(value, path);
       
        return val;
      }
    }
    
    
    
    
    // ---------------
    // TEST
    // ---------------
    
    // gen obj with duplicate references
    let a = { a1: 1, a2: 2 };
    let b = { b1: 3, b2: "4" };
    let obj = { o1: { o2:  a  }, b, a }; // duplicate reference
    a.a3 = [1,2,b];                      // circular reference
    b.b3 = a;                            // circular reference
    
    
    let s = JSON.stringify(obj, refReplacer(), 4);
    
    console.log(s);

    BONUS: and here is inverse function of such serialisation

    function parseRefJSON(json) {
      let objToPath = new Map();
      let pathToObj = new Map();
      let o = JSON.parse(json);
      
      let traverse = (parent, field) => {
        let obj = parent;
        let path = '#REF:$';
    
        if (field !== undefined) {
          obj = parent[field];
          path = objToPath.get(parent) + (Array.isArray(parent) ? `[${field}]` : `${field?'.'+field:''}`);
        }
    
        objToPath.set(obj, path);
        pathToObj.set(path, obj);
        
        let ref = pathToObj.get(obj);
        if (ref) parent[field] = ref;
    
        for (let f in obj) if (obj === Object(obj)) traverse(obj, f);
      }
      
      traverse(o);
      return o;
    }
    
    
    
    // ------------
    // TEST
    // ------------
    
    let s = `{
        "o1": {
            "o2": {
                "a1": 1,
                "a2": 2,
                "a3": [
                    1,
                    2,
                    {
                        "b1": 3,
                        "b2": "4",
                        "b3": "#REF:$.o1.o2"
                    }
                ]
            }
        },
        "b": "#REF:$.o1.o2.a3[2]",
        "a": "#REF:$.o1.o2"
    }`;
    
    console.log('Open Chrome console to see nested fields:');
    let obj = parseRefJSON(s);
    
    console.log(obj);

提交回复
热议问题