node.js - 如何使用 Nodejs 删除 Mongodb 中 JSON 格式数据中的斜线?

标签 node.js mongodb npm

我使用 Nodejs 和 mongoskin 将数据以 JSON 格式存储在 mongo 表中。 Mongo 自动在 json 格式的数据中添加斜线。然后当我检索时,我无法解析数据。请建议我,如何删除斜杠或如何解析数据?

 db.messagetable.find().forEach(printjson)
{
        "_id" : "1861574",
        "MatriId" : "1861574",
        "session" : "{\"messages\":{\"cometchat\":{\"timedifference\":0,\"cometchat_buddytime\":0,\"msgavails\":\"\"}}}",
        "expires" : 1341702134
}

最佳答案

这里的斜杠用于转义 JSON 编码字符串中的字符 "(不是 json 对象,因为

> JSON.parse("{messages:1}")
SyntaxError: Unexpected token m
    at Object.parse (native)
    at repl:1:7
    at REPLServer.eval (repl.js:80:21)
    at Interface.<anonymous> (repl.js:182:12)
    at Interface.emit (events.js:67:17)
    at Interface._onLine (readline.js:162:10)
    at Interface._line (readline.js:426:8)
    at Interface._ttyWrite (readline.js:603:14)
    at ReadStream.<anonymous> (readline.js:82:12)
    at ReadStream.emit (events.js:88:20)

因此键必须用 " 括起来以表示一个字符串,但您不能只将 " 放在字符串中。要修复 json 解析器,请附加 \

 > JSON.parse("{\"messages\":1}")
{ messages: 1 }

所以当你解析时,只需在 session 字符串上调用 JSON.Parse

> JSON.parse("{\"messages\":{\"cometchat\":{\"timedifference\":0,\"cometchat_buddytime\":0,\"msgavails\":\"\"}}}")
{ messages: 
   { cometchat: 
      { timedifference: 0,
        cometchat_buddytime: 0,
        msgavails: '' } } }

关于node.js - 如何使用 Nodejs 删除 Mongodb 中 JSON 格式数据中的斜线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8968248/

相关文章:

javascript - Webpack 在终端中运行时会给出 "error error: unknown option ' -p'"

angular - 使用 Angular 库作为 git 依赖项

javascript - 数组在 node.js 上作为字符串发送

node.js - 如何自动更新所有 Node.js 模块?

javascript - 如何在没有 Node.JS 的情况下最小化 Angular 的打包?

ruby - 如何在控制台中禁用 MongoDB 日志消息?

spring - @DataMongoTest 正在创建一个空的 MongoTemplate

python - 根据 map 中键的存在有选择地检索

c++ - 如何使用 Node C++ 插件部署动态库?

node.js - 使用 Bazel 构建 Node.Js Docker 镜像