0

I create a JSON object with a for loop like this, and the problem is in the JSON keys:

var jsonData = {};
var childDivs = document.querySelector('#markers').children;
for( i=0; i< childDivs.length; i++ ){
    if(childDivs[i].tagName==="DIV" && childDivs[i].children[0].children[0].className==="level0"){
      var module_name_=childDivs[i].id;
      console.log(module_name_+"..") // here it shows correctly : without "\r"

      var coordinates =return_coordinates_of_module(module_name_);
      
      jsonData[module_name_]=[coordinates[0],coordinates[1]];

      }
  }
  console.log(jsonData);

The value of childDivs[i].id is created with this code ( I read a csv file then I use those values as id on my html page)):

if (!this.files || !this.files[0]) return;
const FR = new FileReader();
FR.addEventListener("load", (evt) => {
var x=evt.target.result.split("\n");
x.splice(-1,1);// last element is empty
console.log(x+","+x.length);
var top=180;
var left=0;
for(i in x){
  append_module_name_to_drag_div(x[i],top,left);
 }
}
FR.readAsText(this.files[0],"ISO-8859-3");

and here is the function append_module_name_to_drag_div:

  var mydiv = document.createElement("div");
  console.log(module_name);
  mydiv.id=module_name;
  mydiv.className ='col-sm-10';
  var mydivmarker= document.createElement("div");
  mydivmarker.id=module_name+"header";
  mydivmarker.className ='mydivheader';
  var marker_image = new Image();
  mydiv.style.overflow = "hidden";
  mydiv.style.whiteSpace="nowrap";
  marker_image.src = "http://www.clker.com/cliparts/w/O/e/P/x/i/map marker-hi.png";
  marker_image.height = 45;
  marker_image.width = 35;
  marker_image.className="level0";
  mydivmarker.append(marker_image);
  mydiv.innerHTML=module_name;
  mydiv.append(mydivmarker);
  mydiv.style.left = left.toString()+"px";
  mydiv.style.top = top.toString()+"px";
  document.getElementById("markers").appendChild(mydiv);

  
  
}

When I do console.log(jsonData) it shows a space after keys, when I put the cursoe next of "Beauregard" it shows an "Beauregard\r", as in the following image :

enter image description here

Also with console.log(JSON.stringify(jsonData));:

{"La Pallice\r":[549,213.0078125],"Dor\r":[806.5,245.0078125],"Le Prieuré\r":[874,245.0078125],"Rey Valin\r":[956.5,245.0078125]}

And after came this part of code and when I do console.log() to data["data"] keys it has also \r :

 fetch(`${window.origin}/upload_your_map/create-entry`, {
      method: "POST",
      credentials: "include",
      body: JSON.stringify({
        image:image_to_send_to_backend.src,
        data:jsonData,
        nom_carte:map_name}),
      cache: "no-cache",
      headers: new Headers({
        'content-type': 'application/json; charset="utf-8"'
      })
    })
      .then(function (response) {
        if (response.status !== 200) {
          console.log(`Looks like there was a problem. Status code: ${response.status}`);
          return;
        }
        response.json().then(function (data) {
          console.log(data["data"]);
    });
  })
ab.fe
  • 111
  • 7
  • 2
    What's your question? – Spectric Jul 17 '21 at 17:20
  • I think this has something to do with the data in your array X. Javascript does not add random linebreaks. I think we need more details about the data you used and also please share full code and do not put "...". – Passiv Programmer Jul 17 '21 at 17:50
  • `console.log` modify input for pretty print. But you can `JSON.stringify` your input, then print it in console... To fix this issue: you could trim string with `String.prototype.trim` method... – Nur Jul 17 '21 at 20:53
  • @Spectric my question is : why do I have a `\r` after my JSON object keys? – ab.fe Jul 17 '21 at 21:07
  • @PassivProgrammer I edited the code, hope it's clear now – ab.fe Jul 17 '21 at 21:08
  • @Nur the problem is when I loop over the JSON and I print the keys with `console.log()` it is printed correctly without the `\r` and when the whole object is printed or save it in a JSON file the `\r` appears – ab.fe Jul 17 '21 at 21:13
  • 1
    Threw an answer in. Mods really shouldn't be on this site if they can't bother to read into beginner questions. – Warty Jul 17 '21 at 21:31

1 Answers1

3

In var x=evt.target.result.split("\n"); you're splitting by \n.

On Windows the standard line delimiter is \r\n.

A text file like:

line1
line2

Will be encoded as something like: line1\r\nline2 (assuming no byte-order-marks). Splitting by \n yields [line1\r, line2].

As a workaround, consider either splitting by the correct delimiter or running a trim() on the output elements to remove left/right whitespace in your strings.

"asdf".trim() == "asdf"
"asdf\r".trim() == "asdf"
"asdf  \r  ".trim() == "asdf"
Warty
  • 7,237
  • 1
  • 31
  • 49
  • Thanks it works, even if it was a little bit stupid question, but I am still a beginner and english is my 3rd language... thanks again for your time – ab.fe Jul 17 '21 at 23:57