根据JSON中可用的值将嵌套的json转换为特定格式的字符串

时间:2022-06-20 00:18:05

I have dummy JSON format as follows:

我有如下虚拟JSON格式:

{
    "a":"guig",
    "b":"khih",
    "c":[
      {
        "k1":"ert",
        "k2":"uii"
      },
      {
        "k1":"ert1"
      },
      {
        "k1":"ert2",
        "k2":"uii2"
      }],
    "d":{
      "e":"yfyuf",
      "f":[
        {
          "kk1":"ert",
          "kk2":"uii"
        },
        {
          "kk1":"ert1",
          "kk2":"uii1"
        },
        {
          "kk1":"ert2",
          "kk2":"uii2"
        }
      ]
    },
    "h":78767
  },
  {
    "a":"guig",
    "b":"khih",
    "c":[
      {
        "k1":"ert"
      },
      {
        "k1":"ert1",
        "k2":"uii"
      },
      {
        "k1":"ert2",
        "k2":"uii2"
      }],
    "d":{
      "e":"yfyuf",
      "f":[
        {
          "kk1":"ert",
          "kk2":"uii"
        },
        {
          "kk1":"ert1",
          "kk2":"uii1"
        }
      ]
    },
    "i":78767
  },
 .....

I want to convert the above JSON to string in following format (Basically csv compatible where first line will be header of it):

我想以下面的格式将上面的JSON转换为字符串(基本上csv兼容,其中第一行将是它的标题):

a,    b,    c1_k1, c2_k1, c3_k1, c1_k2, c2_k2, c3_k2, d_e,   d_f1_kk1, d_f2_kk1, d_f3_kk1, d_f1_kk2, d_f2_kk2, d_f3_kk2, h,    i
guig, khih, ert,   ert1,  ert2,  uii,        , uii2,  yfyuf,  ert,     ert1,     ert2,     uii,       uii1,         ,   78767,
guig, khih, ert,   ert1,  ert2,     ,   uii  , uii2,  yfyuf,  ert,     ert1,     ert2,     uii,       uii1,         ,        ,78767,

field like c1,..Cn comes as much as key duplication are available and wherever values are not present the logic should append extra comma for empty cell. Values of any key can be Array, Object or String

字段如c1,.. Cn和密钥复制一样多,并且在没有值的地方,逻辑应该为空单元格附加额外的逗号。任何键的值都可以是Array,Object或String

The Failed logic I tried are following

我试过的失败逻辑正在跟随

Logic:1

逻辑:1

ItrStr=function(k,h) {
        if(typeof k == "string"){
            itsLine+= k+",";
            itsHdr += h+",";
        }else if(k && k.length){
            ItrArr(k);
        } else{
            ItrObj(k);
        }
    },
    ItrArr=function(k) {
        if(k.length){
            k.forEach((o)=>{
                ItrStr(o,"");
            });
        }else{
            ItrObj(k);
        }
    },
    ItrObj=function(k) {
        if(k){
            let itsKs=Object.keys(k);
            itsKs.forEach((o)=> {
                let k1 = k[o];
                ItrStr(k1,o);
            });
        }else {
            itsLine += ",";
            itsHdr += ",";
        }
    };
let ttp=inputJson;
            itsLine="";
            ItrObj(ttp);
            itsLine=itsLine.replace(/\r/g,"").replace(/\n/g,"")+"\n";
            if(!isHdrWrote){
                fs.appendFile(dir,itsHdr);
                isHdrWrote=true;
            }else{
                fs.appendFile(dir,itsLine);
            }

Logic: 2

逻辑:2

findObjectByHDR = function(obj) {
        if(!obj){ return "" }
        if(Array.isArray(obj)) {
            obj.forEach((o)=>{
                if(o){
                    findObjectByHDR(o);
                }
            });
        }else{
            for(let i in obj) {
                if(obj.hasOwnProperty(i)){
                    if(typeof obj[i] == "string" || typeof  obj[i]== "number"){
                        if(i.length == 1){
                            console.log("i: ",i," : ",obj);
                        }
                        if(agrtHdr.indexOf(i)<0){
                            agrtHdr.push(i);
                        }/*else {
                            if(addDups[i]){
                                addDups[i]++;
                            }else{
                                addDups[i]=0;
                            }
                            agrtHdr.push(addDups[i]+"---"+i);
                        }*/
                    }else if(Array.isArray(obj[i])) {
                        obj[i].forEach((o)=>{
                            if(o){
                                //console.log("arr",o);
                                findObjectByHDR(o);
                            }
                        });
                    }else {
                        for(let i1 in obj[i]) {
                            if(obj[i].hasOwnProperty(i1)){
                                if(typeof obj[i][i1] == "string" || typeof  obj[i][i1]== "number"){
                                    if(agrtHdr.indexOf(i1)<0){
                                        agrtHdr.push(i1);
                                    }
                                }else{
                                    findObjectByHDR(obj[i][i1]);
                                }
                            }
                        }
                    }
                }
            }
        }
    },
    findObjectByLBL = function(obj,lbl) {
        if(!obj){ return "" }
        if(Array.isArray(obj)) {
            obj.forEach((o)=>{
                if(o){
                    findObjectByLBL(o,lbl);
                }
            });
        }else if(typeof obj[lbl] == "string" || typeof  obj[lbl]== "number"){
            return ""+obj[lbl];
        }
        else if(typeof obj != "string" && typeof  obj!= "number") {
            for(let i in obj) {
                if(obj.hasOwnProperty(i)){
                    if(Array.isArray(obj[i])) {
                        obj[i].forEach((o)=>{
                            if(o){
                                findObjectByLBL(o,lbl);
                            }
                        });
                    }else if(obj[i]){
                        if(typeof obj[i] != "string" && typeof  obj[i]!= "number"){
                            findObjectByLBL(obj[i],lbl);
                        }
                    }
                }
            }
        }
    }

 let ttp=inputJson;
                itsHdr="";
                var crntLin=[];
                if(!dtRed){
                    findObjectByHDR(ttp);
                }
                if(dtRed){
                    for(let ik=0;ik<agrtHdr.length;ik++){
                        let iitln=findObjectByLabel(ttp,agrtHdr[ik]);
                        if(!iitln){
                            console.log(ik,":",lineNr,"--",agrtHdr[ik]," : agrtHdr: "," : ",iitln);
                        }
                        if(iitln){
                            crntLin.push(iitln.replace(/\r/g,"").replace(/\n/g,""));
                        }else{
                            crntLin.push("");
                        }
                    }
                    fs.appendFile(dir,crntLin.join(",")+"\n");
                }

1 个解决方案

#1


2  

I tried following approach it worked:

我尝试了以下方法:

var dir = path.join(__dirname,'./slack.csv'),
    jsn=require(path.join(__dirname,'./slack.json')),
    itsHdrAll=[],
    itsHdrAllAr=[],
    finlHdr=[],
    findObjectByHDR = function (){
        let obj=arguments[0];
        let arg1=arguments[1];
        if(Array.isArray(obj)){
            obj.forEach((o,i)=>{
                let crntProp=arg1?arg1:[];
                crntProp.push({cameFrm:"Arr",ind:i});
                findObjectByHDR(o,crntProp)
            });
        }else{
            for(let k in obj) {
                if(obj.hasOwnProperty(k)){
                    if(typeof obj[k] == "string" || typeof obj[k] == "number"){
                        let arg1=arguments[1];
                        let itsHdr="";
                        if(arg1){
                            arg1.forEach(o=>{
                                if(o.cameFrm=="Arr"){
                                    if(o.ind !=0){
                                        itsHdr=itsHdr.substring(0,itsHdr.length-4) + o.ind+"___";
                                    }else{
                                        itsHdr+= o.ind+"___";
                                    }
                                }else if(o.cameFrm=="Obj"){
                                    itsHdr+= o.prop+"___";
                                }
                            });
                        }
                        itsHdr += k+"___";
                        itsHdrAll.push(itsHdr);
                    }else {
                        let crntProp=arg1?arg1:[];
                        crntProp.push({cameFrm:"Obj",prop:k});
                        findObjectByHDR(obj[k],crntProp)
                    }
                }
            }
        }
    };
    for(let j=0;j<jsn.length;j++){
        findObjectByHDR(jsn[j]);
        itsHdrAllAr.push(itsHdrAll);
        itsHdrAll=[];
    }
    itsHdrAllAr.forEach(o=>{
        o.forEach(o1=>{
            if(finlHdr.indexOf(o1)<0){
                finlHdr.push(o1);
            }
        });
    });
    finlHdr=finlHdr.map(o=>{
        return o.substring(0,o.length-3);
    });
    finlHdr.sort();
    console.log("finlHdr: ",finlHdr);
    fs.appendFile(dir,finlHdr.join(",")+"\n");

#1


2  

I tried following approach it worked:

我尝试了以下方法:

var dir = path.join(__dirname,'./slack.csv'),
    jsn=require(path.join(__dirname,'./slack.json')),
    itsHdrAll=[],
    itsHdrAllAr=[],
    finlHdr=[],
    findObjectByHDR = function (){
        let obj=arguments[0];
        let arg1=arguments[1];
        if(Array.isArray(obj)){
            obj.forEach((o,i)=>{
                let crntProp=arg1?arg1:[];
                crntProp.push({cameFrm:"Arr",ind:i});
                findObjectByHDR(o,crntProp)
            });
        }else{
            for(let k in obj) {
                if(obj.hasOwnProperty(k)){
                    if(typeof obj[k] == "string" || typeof obj[k] == "number"){
                        let arg1=arguments[1];
                        let itsHdr="";
                        if(arg1){
                            arg1.forEach(o=>{
                                if(o.cameFrm=="Arr"){
                                    if(o.ind !=0){
                                        itsHdr=itsHdr.substring(0,itsHdr.length-4) + o.ind+"___";
                                    }else{
                                        itsHdr+= o.ind+"___";
                                    }
                                }else if(o.cameFrm=="Obj"){
                                    itsHdr+= o.prop+"___";
                                }
                            });
                        }
                        itsHdr += k+"___";
                        itsHdrAll.push(itsHdr);
                    }else {
                        let crntProp=arg1?arg1:[];
                        crntProp.push({cameFrm:"Obj",prop:k});
                        findObjectByHDR(obj[k],crntProp)
                    }
                }
            }
        }
    };
    for(let j=0;j<jsn.length;j++){
        findObjectByHDR(jsn[j]);
        itsHdrAllAr.push(itsHdrAll);
        itsHdrAll=[];
    }
    itsHdrAllAr.forEach(o=>{
        o.forEach(o1=>{
            if(finlHdr.indexOf(o1)<0){
                finlHdr.push(o1);
            }
        });
    });
    finlHdr=finlHdr.map(o=>{
        return o.substring(0,o.length-3);
    });
    finlHdr.sort();
    console.log("finlHdr: ",finlHdr);
    fs.appendFile(dir,finlHdr.join(",")+"\n");