Why are the values of my JSON objects keys undefined?

I need to parse JSON, but the values of the objects keys are undefined:

   const MY_JSON_FILE = "{ "version": "1.0", "result": 4, "id": "1" }x00"
    
     
    
    let json = JSON.stringify(MY_JSON_FILE);
    
     
    
    const blob = new Blob([json], {type:"application/json"});
    
     
    
    const fr = new FileReader();
    
     
    
    var res;
    
    fr.onload = () => {
    
      console.log('done', fr.readyState);
    
      console.log('reader result: ', fr.result);
    
      res = JSON.parse(fr.result);
    
     
     console.log(Object.keys(res));
    
      console.log('parsed: ' + res);
    
      console.log(res.id);
    
      console.log(res.result);
    
      console.log(res.version);
    
    }
    
    fr.readAsText(blob);

The values of my objects keys are undefined after parsing. How can I parse and access the values of my objects keys successfully?

Answer

  1. You start with a string of JSON that represents an object (almost, there is some invalid data at the end).
  2. You use JSON.stringify to convert that to a string of JSON that represents the string in 1.
  3. You convert it to a file and then read it to get back to the string you had at 2
  4. Your parse that string as JSON to get the string you had at 1
  5. You read the Object keys of that string

i.e. you are encoding the object to JSON twice and decoding it only once and then trying to treat the string of JSON as the object that JSON represents.

Remove the invalid data from your original string and parse the JSON from step 4 to an object… better yet skip steps 2 and 3 entirely.

const MY_JSON_FILE = "{ "version": "1.0", "result": 4, "id": "1" }"
const data = JSON.parse(MY_JSON_FILE);
console.log(Object.keys(data));