【问题标题】:Is there a property in javascript Object.type?javascript Object.type 中是否有属性?
【发布时间】:2015-12-15 00:57:49
【问题描述】:

我现在正在研究Node.Js,偶然发现了这段代码:

  var combine = require('stream-combiner');
  var through = require('through2');
  var split = require('split');
  var zlib = require('zlib');

  module.exports = function () {
      var grouper = through(write, end);
      var current;

      function write (line, _, next) {
          if (line.length === 0) return next();
          var row = JSON.parse(line);

          if (row.type === 'genre') {
             if (current) {
                 this.push(JSON.stringify(current) + '\n');
             }
              current = { name: row.name, books: [] };
          }
          else if (row.type === 'book') {
              current.books.push(row.name);
          }
          next();
      }
      function end (next) {
          if (current) {
              this.push(JSON.stringify(current) + '\n');
          }
          next();
      }

      return combine(split(), grouper, zlib.createGzip());
  };

write 函数获取的每一行都是一个 json 行,如下所示:

"name": "Neuromancer","genre": "cyberpunk"

预期的结果是以下 JSON 对象:

{
"name": "cyberpunk",
"books": [
  "Accelerando",
  "Snow Crash",
  "Neuromancer",
  "The Diamond Age",
  "Heavy Weather"
]}

等等。

基本上我的问题是 - row.type 是什么意思?

提前感谢您! :D

【问题讨论】:

  • 它是 JSON 参数 line 中的一个属性。它可能是任何东西 - 无法从中分辨出来
  • 您在哪里找到该代码?你确定它真的有效吗? JSON 样本没有 type 属性,因此如果输入真的是这样,row.type 将始终是 undefined
  • 正是我的想法。它是我用来学习 Node.JS 的 WorkShop 的一部分,所以我猜他们知道自己在做什么。

标签: javascript json node.js object


【解决方案1】:

你把 type 参数放在 var row

var row = JSON.parse(line);

所以这不是对象的特殊属性或函数,它只是 JSON 中的一个参数(var line

【讨论】:

  • 好吧。所以基本上我通过 JSON.parse() 以某种方式向 JSON 添加了类型属性?
猜你喜欢
  • 1970-01-01
  • 2013-07-12
  • 2011-12-17
  • 2012-03-06
  • 2018-04-13
  • 2013-10-18
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
相关资源
最近更新 更多