Timoney, Daniel (dt5972) | 324ee36 | 2017-02-15 10:37:53 -0500 | [diff] [blame^] | 1 | var obj={}; |
| 2 | function dotToJson(str,value,obj){ |
| 3 | //var objArr = path.split("."), part; |
| 4 | var objArr = str.split("."); |
| 5 | var prevStr; |
| 6 | var currObj; |
| 7 | var prevObj; |
| 8 | console.log(str); |
| 9 | for(var i=0;i<objArr.length -1;i++){ |
| 10 | var subStr= objArr[i] ; |
| 11 | //console.log("subStr:" + subStr); |
| 12 | if(i==0 && obj[subStr] == undefined ){ |
| 13 | obj[subStr] = {}; |
| 14 | currObj= obj[subStr]; |
| 15 | }else if(i==0 && obj[subStr] != undefined ){ |
| 16 | currObj=obj[subStr]; |
| 17 | //console.log("in gkjgjkg"); |
| 18 | }else{ |
| 19 | if(i == 1){ |
| 20 | prevObj=obj[prevStr]; |
| 21 | if(prevObj[subStr] == undefined){ |
| 22 | prevObj[subStr] = {}; |
| 23 | currObj = prevObj[subStr]; |
| 24 | }else{ |
| 25 | currObj = prevObj[subStr]; |
| 26 | } |
| 27 | }else{ |
| 28 | if(prevObj[subStr] == undefined){ |
| 29 | prevObj[subStr] = {}; |
| 30 | currObj = prevObj[subStr]; |
| 31 | }else{ |
| 32 | currObj = prevObj[subStr]; |
| 33 | } |
| 34 | } |
| 35 | //console.dir(currObj); |
| 36 | } |
| 37 | prevStr=subStr; |
| 38 | if(i <objArr.length-2){ |
| 39 | prevObj=currObj; |
| 40 | } |
| 41 | } |
| 42 | var lastStr = objArr[objArr.length-1]; |
| 43 | currObj[lastStr] = value; |
| 44 | //prevObj[lastStr] = value; |
| 45 | //console.dir(currObj); |
| 46 | return obj; |
| 47 | } |
| 48 | n=dotToJson('abcfdfghdghdghdghdhdhd.efhfjhfjhfjhfjhfjhfjhfbg.hfjhfjhfjhfjhfjhfjh.l',"1234",obj); |
| 49 | //console.dir(n); |
| 50 | JSON.stringify(n,undefined,2); |
| 51 | m=dotToJson('abc.ebg.h.n',"5678",n); |
| 52 | console.dir(m); |
| 53 | function printObj(obj){ |
| 54 | for( j in obj){ |
| 55 | console.log(j + ":" + obj[j]); |
| 56 | if(typeof obj[j] == "object" ){ |
| 57 | printObj(obj[j]); |
| 58 | } |
| 59 | |
| 60 | } |
| 61 | } |
| 62 | printObj(m); |
| 63 | a=JSON.parse(JSON.stringify(m,null,2)); |
| 64 | console.dir(a); |
| 65 | |
| 66 | |
| 67 | //console.log (stringToObj('abc.ebg.h',"",{})); |