How to turn kamailio dialoge to JSON

When we run a command in kamailio, it gives result in some weired format which is not JSON but looks like JSON. Is there any way to get that response in JSON

Tagged:

Answers

  • sachin
    edited February 8

    In javascript, this is how you can do it,

    var dialogue2json = function(dialogue = ""){
      dialogue = dialogue.replace(/^\t+/gm, "");
    
      if(dialogue.length == 0 || dialogue == "" || dialogue == null){
        return {};
      }
    
      var jsonstring    = "";
      let braceopen     = false;
      let invalidbrace  = false;
      let braceclose    = false;
      let comma         = "";
    
      if(/^error/.test(dialogue)){
        invalidbrace = true;
      }
    
      dialogue.split(/\r?\n/).forEach((line, linekey) =>  {
        if(/^error/.test(line)){
          comma = (braceopen || invalidbrace) ? "" : ",";
          invalidbrace = false;
    
          let key = line.split(":", 1);
          let value = /(?<=\:\s).*(?=$)/.exec(line);
          if(value[0] == "" || value[0] == null){
            value[0] = null;
          }else if(/^\d+$/.test(value[0])){
            value[0] = `${value[0]}`;
          }else{
            value[0] = `"${value[0]}"`;
          }
    
          jsonstring += `${comma}{"${key[0]}":${value[0]}}`;
          braceopen = false;
          braceclose = true;
    
    
        }else if(/^{/.test(line)){
          comma = (braceclose && !braceopen) ? "," : "";
          braceclose = false;
          invalidbrace = (braceopen || invalidbrace) ? true : false;
          let key = (invalidbrace) ? `"${linekey}":` : "";
          jsonstring += `${comma}${key}${line}`;
          braceopen = true;
        }else if(/^.+:\s{/.test(line)){
          comma = (braceopen) ? "" : ",";
          let key = line.split(":", 1);
          jsonstring += `${comma}"${key[0]}":{`;
          braceopen = true;
        }else if(/^.+\:\s(.+)?$/.test(line)){
          comma = (braceopen || invalidbrace) ? "" : ",";
          braceopen = false;
          let key = line.split(":", 1);
          let value = /(?<=\:\s).*(?=$)/.exec(line);
          if(value[0] == "" || value[0] == null){
            value[0] = null;
          }else if(/^\d+$/.test(value[0])){
            value[0] = `${value[0]}`;
          }else{
            value[0] = `"${value[0]}"`;
          }
          jsonstring += `${comma}"${key[0]}":${value[0]}`;
        }else if(/^}$/.test(line)){
          braceopen = false;
          invalidbrace = (braceclose) ? false : invalidbrace;
          jsonstring += `${line}`;
          braceclose = true;
        }else{
        }
      });
    
      jsonstring = `[${jsonstring}]`;
    
      const jsonobj = JSON.parse(jsonstring);
      return jsonobj;
    }
    
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!