Search code examples
javascriptjsonfetchcomparison

Detect from which json tag the chatbot responds comes from


I'm working on a chatbot that uses JSON for its dataset. The JSON file contains a different tag that represents different topics, f.ks 'greeting', 'goodbye' etc. My plan is to have a progress bar to move a certain percent depending on which tag the chatbot response comes from. I'm on the final stage where the chatbot response has to be mapped back to JSON for comprising. I'm stuck on how would I would do it in the simplest way since the data already comes from there?json file image here

<script>
   const url = "http://127.0.0.1:5000/json";
   //const botRep = 
   //const test1 = document.getElemenById('textInput').textContent;
   async function getData(){
   
   const response = await fetch(url);
   const data = await response.json();
   let tag1 = data.intents[0].tag; //greeting tag from json
   console.log(tag1);

   }
    getData();
  
   function botResponse(rawText) {

      // Bot Response
      $.get("/get", { msg: rawText }).done(function (data) {
        console.log(rawText);. 
        console.log(data);
        const msgText = data;
        $.get("/save", { msg: msgText, sender:BOT_NAME})
        appendMessage(BOT_NAME, BOT_IMG, "left", msgText);

      }); 

    } 


  </script>
/*   progress bar div  */

.progress {
  /* display: flex; */
  font-size: medium;
  justify-content: space-between;
  padding: 5px;
  text-align: center;
  /*border-bottom: var(--border);*/
  background: #eee;
  color: #666;
  text-align: left;
}

#id1{
 position: right;   
 right: 50%;
 top: 10px;
 float:  right;
}

#progress30 {
 width: 500px;   
 border: 1px solid black;
 position: relative;
 padding: 3px;
 top: 16px; 
}

#percent {
 position: absolute;   
 left: 50%;
 bottom: 25px;
}

#bar {
 height: 20px;
 background-color: green;
 width: 0%;
}
<body>
  <!-- partial:index.partial.html -->
  <section class="msger">
    <header class="msger-header">
      <div class="msger-header-title">
        <i class="fas fa-bug"></i>Chatbot <i class="fas fa-bug"></i><br>
        
    <div class="progress">
            Trust Bar
    <div id="progress30">
           <span id="percent">0%</span>
           <div id="bar"></div>
    </div>
    </div>


Solution

  • You could use a map to create a dictionary to store the percentage associated with each tag.

    let myMap = new Map([
      ['greeting', 25],
      ['answer', 50],
      ['goodbye', 100],
    ])
    

    After you get the tag from the json, lookup the percentage value in the map and update the value in the span with id percent