简体   繁体   English

在JavaScript和JSON中,为什么是str = JSON.stringify(obj);的结果? 等于 {}?

[英]In JavaScript & JSON, why is the result of str = JSON.stringify(obj); equal to {}?

I'm a recent, self-taught JavaScript & JSON initiate. 我是最近开始自学的JavaScript和JSON初始化程序。 This demi-project is a scrap of my second JavaScript project. 这个demi项目是我的第二个JavaScript项目的一部分。 Please be gentle with me. 请对我好一点。

I am attempting to input a JSON file, stringify it, and output the resulting string. 我试图输入一个JSON文件,对其进行字符串化,然后输出结果字符串。 The file is a JavaScript object. 该文件是一个JavaScript对象。 But when I execute the statement str = JSON.stringify(obj); 但是当我执行语句str = JSON.stringify(obj); I get the result that str === {} . 我得到的结果是str === {}

Why is the stringified file object equal to {}? 为什么字符串化的文件对象等于{}? How can I get it to be a string equal to the JSON file stringified? 如何获取等于已字符串化的JSON文件的字符串?

The JavaScript is: JavaScript是:

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是:

<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: JavaScript的相关输出为:

obj: [object File]

object stringified : {}

The JSON file, composed in BBEdit for Mac and saved as a Unicode (UTF-8) file, is: 由BBEdit for Mac组成并保存为Unicode(UTF-8)文件的JSON文件为:

{
"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 . CodePen: JSON练习上有一支笔。 You will need a local JSON file to input to it. 您将需要一个本地JSON文件来输入。

Any help will be much appreciated 任何帮助都感激不尽

EDIT 01: 编辑01:

OK, I reformatted the JSON file and validated it with an online JSON validator ( Free Online JSON Formatter ). 好的,我重新格式化了JSON文件,并使用了在线JSON验证器( 免费的在线JSON格式器 )对其进行了验证。 I still get the same result. 我仍然得到相同的结果。 (I also inserted a new first paragraph.) (我也插入了新的第一段。)

JSON.stringify ( spec , MDN ) only includes properties that fit all of the following criteria: JSON.stringifyspecMDN )仅包含符合以下所有条件的属性:

  • They are own properties (not ones the object inherits from its prototype) 它们是自己的属性(不是对象从其原型继承属性)
  • They are enumerable properties (eg, the kind that show up on for-in loops) 它们是可枚举的属性(例如,在for-in循环中显示的属性)
  • Their names are strings (not Symbols) 它们的名称是字符串(不是符号)
  • Their values are not undefined or functions 它们的值不是undefined或函数

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. 您尝试转换为JSON的对象似乎仅具有继承或不可枚举的属性,和/或具有undefined值或函数的属性。


Separately, though, just in case there's any confusion: Note that files[0] won't contain the loaded JSON from the file. 不过,以防万一,请单独注意: files[0]不会包含从文件中加载的JSON。 files[0] is just a record for that file in the list of files in the input type="file" . files[0]只是input type="file"中文件列表中该文件的记录。 To load its content, you'd have to use a FileReader . 加载其内容,您必须使用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). 读取它之后(可能使用readAsText ),您将拥有JSON字符串(然后可以使用JSON.parse将其转换为对象结构)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM