1

I'm a recent, self-taught JavaScript & JSON initiate. This demi-project is a scrap of my second JavaScript project. Please be gentle with me.

I am attempting to input a JSON file, stringify it, and output the resulting string. The file is a JavaScript object. But when I execute the statement str = JSON.stringify(obj); I get the result that str === {}.

Why is the stringified file object equal to {}? How can I get it to be a string equal to the JSON file stringified?

The JavaScript is:

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {
        output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a',
        ') - ', f.size, ' bytes, last modified: ' f.lastModifiedDate ?
        f.lastModifiedDate.toLocaleDateString() : 'n/a', '</li>');
    }
    document.getElementById('OutputArea').innerHTML = '<ul>' +
    output.join('') + '</ul>';
    var obj = files[0];
    var str = JSON.stringify(obj);
    document.getElementById( 'OutputArea' ).innerHTML += "obj : " +
    obj + "<br><br>obj stringified : " + str;
}   // end def fn handleFileSelect

// set event listener on InputArea
document.getElementById('InputArea').addEventListener('change',
handleFileSelect, false);

The HTML is:

<html lan="en">
   <head>
      <title="A JSON exercise"></title>
   </head>
   <body>

      <input id="InputArea" name="files[]" type="file" accept="application/json"
      multiple />
      <output id="OutputArea"</output>

   </body>
</html>

The relevant output of the JavaScript is:

obj: [object File]

object stringified : {}

The JSON file, composed in BBEdit for Mac and saved as a Unicode (UTF-8) file, is:

{
"FHC-Class-Schedule" : [

    {
        "time" : "0830",
        "room" : "A-I",
        "classTitle" : 
            "Keynote Address",
        "classDescription" : 
            "Room I [content to come]",
        "instructorName" : "Crista Cowen",
        "instructorGender" : "female",
        "instructorBio" : 
            "Crista Cowan has been employed by Ancestry.com since 2004.",
        "instructorImgHref" : 
            ""
    }
  ]
}

There is a pen at CodePen: A JSON Exercise. You will need a local JSON file to input to it.

Any help will be much appreciated

EDIT 01:

OK, I reformatted the JSON file and validated it with an online JSON validator (Free Online JSON Formatter). I still get the same result. (I also inserted a new first paragraph.)

alxfyv
  • 389
  • 1
  • 6
  • 18

1 Answers1

4

JSON.stringify (spec, MDN) only includes properties that fit all of the following criteria:

  • They are own properties (not ones the object inherits from its prototype)
  • They are enumerable properties (e.g., the kind that show up on for-in loops)
  • Their names are strings (not Symbols)
  • Their values are not undefined or functions

The object you're trying to convert to JSON would appear to only have inherited or non-enumerable properties, and/or ones whose values are undefined or functions.


Separately, though, just in case there's any confusion: Note that files[0] won't contain the loaded JSON from the file. files[0] is just a record for that file in the list of files in the input type="file". To load its content, you'd have to use a FileReader. This answer (of mine) shows how to do that. Once you'd read it (probably using readAsText), you'd have the JSON string (and then could use JSON.parse to convert it to an object structure).

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Worth including a link to the spec that describes that behaviour: http://www.ecma-international.org/ecma-262/6.0/#sec-json.stringify (see NOTE 5 and NOTE 6) – kamituel Mar 02 '17 at 08:40
  • @kamituel: Not *quite* ninja, because of your comment. :-) – T.J. Crowder Mar 02 '17 at 08:40
  • @T.J.Crowder I believe I understand what you are saying. It seems I have much more research to do. Thanks so much for the extensive and informative answer. Your closing paragraph ("Separately, though, ...") is very helpful. For me, it's the meat of the answer, though it seems to have been an afterthought for you. – alxfyv Mar 02 '17 at 09:32
  • @alxfyv :-) Sort of, at first I thought you were trying to turn that file record (not contents) into a JSON string to send to the server or something. Then I thought "Well, why would he include the JSON file in the question then?" and figured I'd cover my bases. – T.J. Crowder Mar 02 '17 at 09:41