javascript JSON.parse 如何管理“未定义”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17648150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:04:52  来源:igfitidea点击:

How does JSON.parse manage 'undefined'?

javascriptjson

提问by Braiam

I transformed this:

我改变了这个:

function MangaElt(obj) {
  "use strict";
  this.mirror = obj.mirror;
  this.name = obj.name;
  this.url = obj.url;
  if (obj.lastChapterReadURL !== undefined) {
    this.lastChapterReadURL = obj.lastChapterReadURL;
    this.lastChapterReadName = obj.lastChapterReadName;
  } else {
    this.lastChapterReadURL = null;
    this.lastChapterReadName = null;
  }
  this.listChaps = [];
  if (obj.listChaps !== undefined && obj.listChaps !== null && obj.listChaps !== "null") {
    if (!isArray(obj.listChaps)) {
      this.listChaps = JSON.parse(obj.listChaps);
    }
  }
  this.read = 0;
  if (obj.read !== undefined && obj.read !== null && obj.read !== "null") {
    this.read = obj.read;
  }
}

Into this:

进入这个:

function MangaElt(obj) {
  "use strict";
  this.mirror = obj.mirror;
  this.name = obj.name;
  this.url = obj.url;
  this.lastChapterReadURL = obj.lastChapterReadURL || null;
  this.lastChapterReadName = obj.lastChapterReadName || null;
  this.listChaps = JSON.parse(obj.listChaps) || [];
  this.read = obj.read || 0;
  this.update = obj.update || 1;
}

As you can see, the code is now more readable and compact. The snippet works under normal circumstances just fine. The thing is that I don't have sometimes all the values in the objobject, so, I expect some undefined's here and there. And that is the reason of my questions:

如您所见,代码现在更具可读性和紧凑性。该代码段在正常情况下工作得很好。问题是有时我没有obj对象中的所有值,所以,我希望undefined这里和那里有一些。这就是我提出问题的原因:

  1. Why JSON.parseinterpret a undefinedas string, trowing as say the MDN, "syntax error" for undefined?
  2. Should then, I, check before the values get parsed if the value is a proper string?
  3. Shouldn't JSON.parse, check whenever the value parsed is undefinedand just return undefined? (This may rise arguments, so, if you believe that is good as is, just ignore this question or state that I'm just wrong with my train of trough)
  4. If #2 is affirmative, then just adding some conditional as the first snipped should be enough, right? Or should I go to the function that calls MangaElt and make sure that obj.listChapsis an array and forget about JSON.parsehere?. (This is always an arrayor a pseudo-array in a string, and since this is a collaborative project, someone may have a reason for this)
  1. 为什么JSON.parse将 a 解释undefined为字符串,如MDN所说,“语法错误” undefined
  2. 那么,我是否应该在解析值之前检查该值是否是正确的字符串?
  3. JSON.parse 不应该检查解析的值undefined并返回undefined吗?(这可能会引起争论,因此,如果您认为这很好,请忽略此问题或声明我的低谷列车错了)
  4. 如果#2 是肯定的,那么只需添加一些条件作为第一个剪断就足够了,对吧?或者我应该去调用 MangaElt 的函数并确保它obj.listChaps是一个数组并忘记JSON.parse这里?。(这始终是字符串中的数组或伪数组,而且由于这是一个协作项目,因此有人可能对此有理由)

For the curious that may ask, 'what's the error you are getting?' is this:

好奇的人可能会问,“你遇到了什么错误?” 这是:

Error in event handler for 'undefined': Unexpected token u SyntaxError: Unexpected token u
at Object.parse (native)
at new MangaElt (chrome-extension://nhjloagockgobfpopemejpgjjechcpfd/js/MangaElt.js:44:25)
at readManga (chrome-extension://nhjloagockgobfpopemejpgjjechcpfd/js/background.js:410:24)
at chrome-extension://nhjloagockgobfpopemejpgjjechcpfd/js/background.js:607:9
at Event.dispatchToListener (event_bindings:356:21)
at Event.dispatch_ (event_bindings:342:27)
at Event.dispatch (event_bindings:362:17)
at miscellaneous_bindings:165:24
at Event.dispatchToListener (event_bindings:356:21)
at Event.dispatch_ (event_bindings:342:27) event_bindings:346

EDIT: This is what already existing entries looks like, which do not generate errors. This scenariois what motivated my question. The type of keys are always the same and are tested beforehand:

编辑:这是已经存在的条目的样子,不会产生错误。这个场景是我提出问题的动机。键的类型总是相同的,并且事先经过测试:

  • nameis a string
  • mirroris a string
  • urlis a string
  • listChapsis an "array" inside a string
  • tsand uptsare integers
  • name是一个字符串
  • mirror是一个字符串
  • url是一个字符串
  • listChaps是字符串中的“数组”
  • ts并且upts是整数

BTW, objis an object, but I think that it's almost impossible to miss. Also, this is a Chrome extension, but I don't think that's relevant. Complete script here.

BTW,obj是一个对象,但我认为它几乎不可能错过。此外,这是一个 Chrome 扩展程序,但我认为这无关紧要。在这里完成脚本。

回答by matt3141

undefinedis not a valid JSON token. When converting an undefined value to JSON, the correct practice is to render it as null.

undefined不是有效的 JSON 令牌。将未定义的值转换为 JSON 时,正确的做法是将其呈现为 null。

回答by Alnitak

  1. undefinedis not a legal token in a JSON file (see www.json.org) nor is it an acceptable parameter to JSON.parse
  2. Your code is not semantically identical to the previous version. Many of the tests in the previous version are more exhaustive (and less error prone) than your new version
  3. Why "refactor" that code if worked as desired? You have not refactored it - you've brokenit.
  1. undefined不是 JSON 文件中的合法标记(参见 www.json.org),也不是可接受的参数 JSON.parse
  2. 您的代码在语义上与以前的版本不同。以前版本中的许多测试比新版本更详尽(并且不易出错)
  3. 如果按预期工作,为什么要“重构”该代码?你还没有重构它——你已经破坏了它。