节点JS [Object Map]在将对象写入文件时

时间:2018-03-25 06:45:22

标签: javascript json node.js

我在stackoverflow和其他教程网站上阅读了很多关于将对象/ JSON写入文件的帖子,但没有一个解决方案适用于我。

1)代码:

let messages = await fetchMessages()
console.log(messages)    // Prints an object
fs.writeFileSync('./msgdata.json', messages , 'utf-8'); 

2)也尝试了,

fs.writeFileSync('./msgdata.json', JSON.stringify(messages) , 'utf-8'); 

3)也尝试了,

fs.writeFile(),但获得与上面相同的输出。

msgdata.json :(适用于1)

[object Map]

msgdata.json :(适用于2& 3)

{}

有人可以指出导致这种情况的原因吗?

## console.log(消息)##

的输出
OUTPUT contains 10 more such objects having different id's:

channel:
   TextChannel {
     type: 'text',
     id: '424825532274253312',
     name: 'request',
     position: 69,
     parentID: '397363224286473987',
     permissionOverwrites: [Object],
     topic: null,
     nsfw: false,
     lastMessageID: '427143105410760704',
     guild: [Object],
     messages: [Object],
     _typing: Map {} },
  id: '427142596817846272',
  type: 'DEFAULT',
  content: '**Select your emoji:** __***Group 9:***__',
  author:
   ClientUser {
     id: '407083773537350272',
     username: 'Bot',
     discriminator: '9256',
     avatar: '9c374e719ba2ab4e69fd577005b635bf',
     bot: true,
     lastMessageID: null,
     lastMessage: null,
     verified: true,
     email: null,
     localPresence: {},
     _typing: Map {},
     friends: Collection {},
     blocked: Collection {},
     notes: Collection {},
     premium: null,
     mfaEnabled: false,
     mobile: null,
     settings: [Object],
     guildSettings: Collection {} },
  member:
   GuildMember {
     guild: [Object],
     user: [Object],
     _roles: [Array],
     serverDeaf: false,
     serverMute: false,
     selfMute: undefined,
     selfDeaf: undefined,
     voiceSessionID: undefined,
     voiceChannelID: undefined,
     speaking: false,
     nickname: null,
     joinedTimestamp: 1517127343434,
     lastMessageID: null,
     lastMessage: null },
  pinned: false,
  tts: false,
  nonce: undefined,
  system: false,
  embeds: [],
  attachments: Collection {},
  createdTimestamp: 1521909131007,
  editedTimestamp: null,
  reactions:
   Collection {
     'taillow:417281639777959940' => [Object],
     'shroomish:417281639899463680' => [Object],
     'sableye:417281640197521419' => [Object],
     'ralts:417281642735075329' => [Object],
     'sentret:417281644001624076' => [Object],
     'shuppet:417281644291162132' => [Object],
     'torchic:417281647210397706' => [Object],
     'snubbull:417281647692480522' => [Object],
     'sunkern:417281647763783681' => [Object],
     'slowpoke:417281648653107200' => [Object],
     'teddiursa:417281649537974273' => [Object],
     'sneasel:417281649613471747' => [Object],
     'snorunt:417281649819123712' => [Object],
     'surskit:417281650163056640' => [Object],
     'qwilfish:417281654629859348' => [Object],
     'shelgon:417281654730522624' => [Object] },
  mentions:
   MessageMentions {
     everyone: false,
     users: Collection {},
     roles: Collection {},
     _content: '**Select your emoji:** __***Group
9:***__',
     _client: [Object],
     _guild: [Object],
     _members: null,
     _channels: null },
  webhookID: null,
  hit: null,
  _edits: [] },

3 个答案:

答案 0 :(得分:3)

这是因为返回的对象是Map对象(MDN)。当您JSON.strigify一个Map对象时,它总是返回{}。有两种方法可以获得存储地图的可读JSON。第一种是遍历所有条目并创建JSON(考虑到键和值)。这应该很容易实现。

另一种方法是从Map创建一个数组,然后将其字符串化。

fs.writeFileSync('./msgdata.json', JSON.stringify([...myObject]) , 'utf-8'); 

答案 1 :(得分:0)

您可以定义哪个有效<script src="https://static.fusioncharts.com/code/latest/fusioncharts.js"></script> <script src="https://csm.fusioncharts.com/projects/themes/hulk-light.js"></script> <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> <div id="chart-container">FusionCharts will render here</div>,但它不是标准的,不鼓励使用。如果Map.prototype.toJSON找到它,它将自动调用。

JSON.stringify

如果您需要从JSON重建地图,更好的方法是定义您自己的Map.prototype.toJSON = function() {return [...this];}; console.log(JSON.stringify(messages)); 函数(和replacer函数)。在这里,我还将表示数组的地图包装在一个特殊的对象中,以便用JSON告诉地图和普通数组:

reviver

关于循环结构的错误意味着某些对象/数组包含对自身的引用。存储邮件时,您不需要存储与频道等相关的所有信息,而只需存储ID。这意味着为function replacer (key, value) { if (value instanceof Map) { return { _type: "map", map: [...value], } } else return value; } function reviver (key, value) { if (value._type == "map") return new Map(value.map); else return value; } let str = JSON.stringify(messages, replacer); let msg = JSON.parse(str, reviver); replacerTextChannel等扩展ClientUser

GuildMember

答案 2 :(得分:0)

var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');

参考Write objects into file with Node.js