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.)