Search code examples
javascriptjavascript-objects

Conversion response XMLHttpRequest into JSON wiht javascrip but the object is null


I'm a greenhorn with Javascript,now I have a problem how when got to convert the response from object XMLHttpRequest into object javascript with JSON.parse(response)

So the my problem is

I do load the file to my local directory, nameProject/app/resources/ with the XMLHttpRequest with this code

the code for creating a request

function readResourcesFile(pathFile, callback) {
  let confFile = new XMLHttpRequest();
  confFile.open('GET', pathFile, true);
  confFile.setRequestHeader('Content-Type', 'application/json');
  let configuration;
  confFile.onreadystatechange = function(){
    if (confFile.readyState === 4) {  // document is ready to parse.
      if (confFile.status === 200) {  // file is found
        let response = confFile.responseText;
        callback(response);
      }
    }
  };
  confFile.send(null);
}

The my final request

function readAllBenchmark() {
  readResourcesFile(rootPath + 'conf/benchmark-conf.json', function (configuration) {
    let objectConf = JSON.parse(configuration);
    console.debug('Configuration object');
    console.debug(objectConf);
    let files = objectConf.files;
    for(let i = 0; i < files.length; i++){
      console.debug('Road this file: ' + files[i]);
      readResourcesFile(rootPath + 'benchmark/' + files[i].toString(), function (fileBenchmark) {
        console.debug('File benchmark: \n' + files[i] + ' with data\n' + fileBenchmark);
        let objectBenchmark = JSON.parse(fileBenchmark);
        console.log('The object benchmark' + objectBenchmark);
        let newData = {
          label: files[i].split('.')[0],
          data: [
            convertNenosecondToSecond(objectBenchmark.benchmarks[0]), convertNenosecondToSecond(objectBenchmark.benchmarks[1])
          ],
          backgroundColor: [
            'rgba(54, 162, 235, 0.2)',
            'rgba(54, 162, 235, 0.2)',
          ],
          borderColor: [
            'rgba(54, 162, 235, 1)',
            'rgba(54, 162, 235, 1)',
          ],
          borderWidth: 2
        };
        addDataToChart(chartBenchmark, ['JSON', 'GraphTx'], newData);
      });
    }
  });
}

My console log

Configuration object
Object
Road this file: i5-6300U@4x_3GH_gcc7.4.0.json
Road this file: [email protected]

File benchmark: 
[email protected] with data
{
  "context": {
    "date": "2019-09-20 20:23:27",
    "host_name": "vincenzo",
    "executable": "./SpyCBlock-benchmarck",
    "num_cpus": 4,
    "mhz_per_cpu": 3000,
    "cpu_scaling_enabled": true,
    "caches": [
      {
        "type": "Data",
        "level": 1,
        "size": 32000000,
        "num_sharing": 2
      },
      {
        "type": "Instruction",
        "level": 1,
        "size": 32000000,
        "num_sharing": 2
      },
      {
        "type": "Unified",
        "level": 2,
        "size": 256000000,
        "num_sharing": 2
      },
      {
        "type": "Unified",
        "level": 3,
        "size": 3072000000,
        "num_sharing": 4
      }
    ],
    "load_avg": [2.01,1.67,1.8],
    "library_build_type": "debug"
  },
  "benchmarks": [
    {
      "name": "BM_createGraphTxOneFile/8",
      "run_name": "BM_createGraphTxOneFile/8",
      "run_type": "iteration",
      "repetitions": 0,
      "repetition_index": 0,
      "threads": 1,
      "iterations": 1,
      "real_time": 1.5634459013000015e+11,
      "cpu_time": 1.5495989063700000e+11,
      "time_unit": "ns"
    },
    {
      "name": "BM_decodeJsonOneFile/8",
      "run_name": "BM_decodeJsonOneFile/8",
      "run_type": "iteration",
      "repetitions": 0,
      "repetition_index": 0,
      "threads": 1,
      "iterations": 1,
      "real_time": 1.9378052880600446e+11,
      "cpu_time": 1.8018651470500000e+11,
      "time_unit": "ns"
    }
  ]
}

The object benchmark[object Object]

why if run this code my code work

console.debug('File benchmark: \n' + files[i] + ' with data\n' + fileBenchmark);

and with this no?

let objectBenchmark = JSON.parse(fileBenchmark);

Update code and using the fetch object

function readResourcesFileFetch(pathFile) {
    return fetch(pathFile, {
      method: 'GET', // *GET, POST, PUT, DELETE, etc.
      cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
      headers: {
        'Content-Type': 'application/json',
        // 'Content-Type': 'application/x-www-form-urlencoded',
      },
      referrer: 'no-referrer', // no-referrer, *client
     // body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
      .then(response => response.json()); // parses JSON response into native JavaScript objects
}


function readAllBenchmarkFetch() {
  let configuration = readResourcesFileFetch(rootPath + 'conf/benchmark-conf.json');
  configuration.then(function (confFile) {
    console.log(confFile);
    let files = confFile.files;
    for(let i = 0; i < files.length; i++){
      console.debug('Road this file: ' + files[i]);
      let singleBenchmark = readResourcesFileFetch(rootPath + 'benchmark/' + files[i].toString());
      singleBenchmark.then(function (fileBenchmark) {
        console.debug('File benchmark: \n' + files[i] + ' with data\n' + fileBenchmark.toString());
        let newData = {
          label: files[i].split('.')[0],
          data: [
            convertNenosecondToSecond(fileBenchmark.benchmarks[0]), convertNenosecondToSecond(fileBenchmark.benchmarks[1])
          ],
          backgroundColor: [
            'rgba(54, 162, 235, 0.2)',
            'rgba(54, 162, 235, 0.2)',
          ],
          borderColor: [
            'rgba(54, 162, 235, 1)',
            'rgba(54, 162, 235, 1)',
          ],
          borderWidth: 2
        };
        addDataToChart(chartBenchmark, ['JSON', 'GraphTx'], newData);
      });
    }
  })
}

Solution

  • When you write console.log(someobject), the browsers are clever, and keep in mind that you were logging an object, and thus you will see an object in the console.
    When you write console.log("Object is "+someobject), the JavaScript engine converts the object to string and appends the result after the text Object is. And stringifying an object indeed results in [object Object] by default.
    One workaround-attempt you can do is using , instead of +, resulting in two logs next to each other:

    var someobject={};
    console.log(someobject);
    console.log("Someobject is "+someobject);
    console.log("Someobject:", someobject);

    (When running the snippet, you will see something here already, but you may want to open the console of your browser too)